我想通过使用if- data语句向我的数据框架(县)添加一个新列(类)。
dataframe:

这是我的密码
#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)下面是我在控制台中收到的错误的屏幕截图:

我做错了什么?有更好的方法吗?蒂娅!
发布于 2021-11-22 00:32:34
我不确定您的数据,但是在您的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
))发布于 2021-11-22 03:36:25
我喜欢帕克的回答。但是,如果您不想使用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)))https://stackoverflow.com/questions/70059747
复制相似问题