[英]Assigning grade and adding that as new column
我想根据分数给学生打分。 我的数据框
Students Subject1 Subject2 subject3 Total
S1 20 10 15 45
S2 10 10 12 32
S3 5 10 10 25
S4 8 10 15 33
S5 6 5 5 16
S6 10 -5 -5 0
我想检查总计是否>30
然后分配P,如果<30
,则分配A,否则为0
输出量
student Subject1 Subject2 subject3 Total Grade
S1 20 10 15 45 P
S2 10 10 12 32 P
S3 5 10 10 25 F
S4 8 10 15 33 P
S5 6 5 5 16 F
S6 10 -5 -5 0 0
我尝试了这段代码
df$Grade <- ifelse(df$Total==0, '0',
ifelse(df$Total < 30, 'A',ifelse(df$Total >30,'P')))
但是我认为这不是正确的方法。
Error in ifelse(df$Total == 0, "0", ifelse(df$Total < :
error in evaluating the argument 'no' in selecting a method for function 'ifelse': Error in ifelse(df$Total < 30, "A", ifelse(df$Total > :
error in evaluating the argument 'no' in selecting a method for function 'ifelse': Error in ifelse(df$Total > 30, "P") :
argument "no" is missing, with no default
您可以考虑cut
功能:
cut(mydf$Total, c(-Inf, 0, 30, Inf), labels = c(0, "F", "P"))
## [1] P P F P F
## Levels: 0 F P
上面的内容基本上说是将-Inf
到0的分数-Inf
为“ 0”,将0和30之间的分数-Inf
为“ F”,将30和Inf
之间的分数-Inf
为“ P”。 因此,如果您的分数向量为c(0, 12, 30, 31, 12, 0, 40)
,您将得到:
cut(c(0, 12, 30, 31, 12, 0, 40), c(-Inf, 0, 30, Inf), labels = c(0, "F", "P"))
## [1] 0 F F P F 0 P
## Levels: 0 F P
使用data.table
包的另一种可能的解决方案:
library(data.table)
setDT(df)
df[,grade:=ifelse(Total==0,"0",ifelse(Total>=30,"P",ifelse(Total %in% 1:30,"A","N")))]
您没有说明在Total==30
情况下期望的grade
,因此我将其编码为P,您可能需要根据需要进行更正。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.