简体   繁体   English

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

[英]Assigning grade and adding that as new column

I want to grade the students on the basis of score . 我想根据分数给学生打分。 My data frame 我的数据框

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

I want to check if the Total is >30 then assign P , if <30 then A, else 0 我想检查总计是否>30然后分配P,如果<30 ,则分配A,否则为0

Output 输出量

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

i tried this code 我尝试了这段代码

df$Grade <- ifelse(df$Total==0, '0',
                                    ifelse(df$Total < 30, 'A',ifelse(df$Total >30,'P')))

But i think its not a correct way. 但是我认为这不是正确的方法。

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

You can consider the cut function: 您可以考虑cut功能:

cut(mydf$Total, c(-Inf, 0, 30, Inf), labels = c(0, "F", "P"))
## [1] P P F P F
## Levels: 0 F P

The above basically says to categorize scores from -Inf to 0 as "0", scores between 0 and 30 as "F", and scores between 30 and Inf as "P". 上面的内容基本上说是将-Inf到0的分数-Inf为“ 0”,将0和30之间的分数-Inf为“ F”,将30和Inf之间的分数-Inf为“ P”。 Thus, if your vector of scores were c(0, 12, 30, 31, 12, 0, 40) , you would get: 因此,如果您的分数向量为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

Another possible solution using data.table package: 使用data.table包的另一种可能的解决方案:

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

You didn't stated what the expected grade should be in case Total==30 , hence I coded it as P, you may want to correct it as needed. 您没有说明在Total==30情况下期望的grade ,因此我将其编码为P,您可能需要根据需要进行更正。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM