使用if else语句添加列

Rob*_*Rob 1 if-statement r dataframe dplyr

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

我在以下代码中复制了与遇到问题的数据帧类似的数据帧。

df <- tibble(score = rnorm(20:100, n = 150))
Run Code Online (Sandbox Code Playgroud)

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

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"
  }
  )
Run Code Online (Sandbox Code Playgroud)

代码执行时显示警告:

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
Run Code Online (Sandbox Code Playgroud)

结果是,所有分数都被分配为“ F”

Ben*_*ker 6

怎么样

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

rev(LETTERS[c(1:4,6)])可能是太聪明,不保存在许多人物c("F","D","C","B","A")...