使用 if, else 语句将新列添加到数据框
add new column to dataframe with if, else statement
我想使用 if-else 语句向我的数据框(县)添加一个新列 (class)。
数据帧:
这是我的代码
#set working directory
setwd("C:/Users/weirc/OneDrive/Desktop/Undergrad Courses/Fall 2021 Classes/GHY 3814/final project/data")
#load packages
library(readr)
library(dplyr)
#load data
counties <- read_csv("vaxData_counties.csv")
calc <- if (counties$Series_Complete >= 75) {
print(4)
} else if (counties$Series_Complete >= 50) {
print(3)
} else if (counties$Series_Complete >= 25) {
print(2)
}else print(1)
#create new column for class
counties %>% mutate(class=calc)
这是我在控制台中收到的错误的屏幕截图:
我做错了什么?有一个更好的方法吗? TIA!
我不确定你的数据,但在你的 if-else if-else
声明中,像 counties$Series_Complete >= 75
这样的条件现在正在将整个向量与单个值进行比较,如果使用 print
,它可能不会给你正确的结果。相反,请尝试使用 dplyr::case_when
library(dplyr)
counties %>%
mutate(class = case_when(
Series_Complete >=75 ~ 4,
Series_Complete >= 50 ~ 3,
Series_Complete >= 25 ~ 2,
TRUE ~ 1
))
我喜欢@Park 的回答。如果您不想使用 dplyr
,您可以使用 ifelse
。您可以链接 ifelse
来模仿 case when
语句的行为:https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/ifelse
counties$class <- ifelse(counties$Series_Complete >= 75, 4,
ifelse(counties$Series_Complete >= 50, 3,
ifelse(counties$Series_Complete >= 25, 2, 1)))
我想使用 if-else 语句向我的数据框(县)添加一个新列 (class)。
数据帧:
这是我的代码
#set working directory
setwd("C:/Users/weirc/OneDrive/Desktop/Undergrad Courses/Fall 2021 Classes/GHY 3814/final project/data")
#load packages
library(readr)
library(dplyr)
#load data
counties <- read_csv("vaxData_counties.csv")
calc <- if (counties$Series_Complete >= 75) {
print(4)
} else if (counties$Series_Complete >= 50) {
print(3)
} else if (counties$Series_Complete >= 25) {
print(2)
}else print(1)
#create new column for class
counties %>% mutate(class=calc)
这是我在控制台中收到的错误的屏幕截图:
我做错了什么?有一个更好的方法吗? TIA!
我不确定你的数据,但在你的 if-else if-else
声明中,像 counties$Series_Complete >= 75
这样的条件现在正在将整个向量与单个值进行比较,如果使用 print
,它可能不会给你正确的结果。相反,请尝试使用 dplyr::case_when
library(dplyr)
counties %>%
mutate(class = case_when(
Series_Complete >=75 ~ 4,
Series_Complete >= 50 ~ 3,
Series_Complete >= 25 ~ 2,
TRUE ~ 1
))
我喜欢@Park 的回答。如果您不想使用 dplyr
,您可以使用 ifelse
。您可以链接 ifelse
来模仿 case when
语句的行为:https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/ifelse
counties$class <- ifelse(counties$Series_Complete >= 75, 4,
ifelse(counties$Series_Complete >= 50, 3,
ifelse(counties$Series_Complete >= 25, 2, 1)))