【问题标题】:Adding a column with an if else statement使用 if else 语句添加列
【发布时间】:2020-02-21 18:19:07
【问题描述】:

我正在尝试将数字划分为类别以创建一个新列。基本上,尝试根据分数创建一个字母等级(“A”、“B”、“C”、“D”、“F”)。

我已经复制了一个与我在以下代码中遇到问题的数据框相似的数据框。

df <- tibble(score = rnorm(20:100, n = 150))

我编写的添加成绩列的代码如下所示:

df_with_grade <- df %>% 
  mutate(Grade = if (score >= 90) {
    "A"
  } else if (score >= 80){
    "B"
  } else if (score >= 70){
    "C"
  } else if (score >= 60){
    "D"
  } else {
    "F"
  }
  )

代码执行时出现警告:

Warning messages:
1: In if (score >= 90) { :
  the condition has length > 1 and only the first element will be used
2: In if (score >= 80) { :
  the condition has length > 1 and only the first element will be used
3: In if (score >= 70) { :
  the condition has length > 1 and only the first element will be used
4: In if (score >= 60) { :
  the condition has length > 1 and only the first element will be used

结果是,所有分数都被分配了一个“F”

【问题讨论】:

  • 尝试使用case_when
  • 如果这些答案中的一个或多个解决了您的问题,我们鼓励您选择您认为最好的一个并单击复选标记...

标签: r dataframe if-statement dplyr


【解决方案1】:

怎么样

cut(df$score,breaks=c(0,6:10)*10,labels=rev(LETTERS[c(1:4,6)]))

rev(LETTERS[c(1:4,6)]) 可能太聪明了,不会在c("F","D","C","B","A") 上保存那么多个字符...

【讨论】:

    【解决方案2】:

    根据 cmets 的建议,您可以使用 case_when:

    df_with_grade <- df %>% 
      mutate(Grade = case_when(score >= 90 ~ "A",
                               score >= 80 ~ "B",
                               score >= 70 ~ "C",
                               score >= 60 ~ "D",
                                         TRUE ~ "F"))
    

    【讨论】:

    • 建议将 T 更改为 TRUE(最佳做法)
    【解决方案3】:

    您不能使用 ifelse,它只适用于二进制条件。像下面这样使用 cut,

    df$Grade = cut(df$score,
    breaks=c(0,60,70,80,90,100),
    label=c("F","D","C","B","A"),
    include.lowest =TRUE)
    

    【讨论】:

      【解决方案4】:

      只是为了表明您可以使用ifelse

      df_with_grade <- df %>% 
        mutate(Grade = 
      ifelse(score>= 90, "A", 
        ifelse(score>=80, "B", 
          ifelse(score>=70, "C", 
            ifelse(score>=60, "D", 
              "F")))) 
          )
      

      【讨论】:

      • 你可以nest ifelse 也是矢量化的。
      猜你喜欢
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      • 1970-01-01
      相关资源
      最近更新 更多