我想使用 if-else 陳述句向我的資料框(縣)添加一個新列(類)。
資料框:

這是我的代碼
#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)
這是我在控制臺中收到的錯誤的螢屏截圖:

我究竟做錯了什么?有一個更好的方法嗎?蒂亞!
uj5u.com熱心網友回復:
我不確定你的資料,但在你的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
))
uj5u.com熱心網友回復:
我喜歡@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)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/364849.html
