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
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(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". Thus, if your vector of scores were c(0, 12, 30, 31, 12, 0, 40)
, you would get:
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.