分配成绩并将其添加为新列

时间:2015-07-02 05:47:22

标签: r

我想根据分数对学生进行评分。我的数据框

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

2 个答案:

答案 0 :(得分:1)

您可以考虑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&#34; 0&#34;分数在0到30之间为&#34; F&#34;以及分数在30和{{ 1}} as&#34; P&#34;。因此,如果你的分数矢量是Inf,你会得到:

c(0, 12, 30, 31, 12, 0, 40)

答案 1 :(得分:0)

使用data.table包的另一种可能的解决方案:

library(data.table)
setDT(df)
df[,grade:=ifelse(Total==0,"0",ifelse(Total>=30,"P",ifelse(Total %in% 1:30,"A","N")))]

您没有说明grade的预期Total==30应该是什么,因此我将其编码为P,您可能需要根据需要进行更正。