【问题标题】:add new column to dataframe with if, else statement使用 if, else 语句向数据框添加新列
【发布时间】:2021-12-31 16:45:18
【问题描述】:

我想使用 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)

这是我在控制台中收到的错误的屏幕截图:

我做错了什么?有一个更好的方法吗?蒂亚!

【问题讨论】:

    标签: r dataframe if-statement data-manipulation


    【解决方案1】:

    我不确定您的数据,但在您的if-else if-else 语句中,像counties$Series_Complete &gt;= 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
      ))
    

    【讨论】:

    • 工作得很好,感谢您! @公园
    【解决方案2】:

    我喜欢@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)))
    

    【讨论】:

      猜你喜欢
      • 2020-02-21
      • 2015-09-03
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      • 2016-10-13
      相关资源
      最近更新 更多