【发布时间】: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