r - Assigning grade and adding that as new column -


i want grade students on basis of score . 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 check if total >30 assign p , if <30 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 code

df$grade <- ifelse(df$total==0, '0',                                     ifelse(df$total < 30, 'a',ifelse(df$total >30,'p'))) 

but think not correct way.

error in ifelse(df$total == 0, "0", ifelse(df$total <  :    error in evaluating argument 'no' in selecting method function 'ifelse': error in ifelse(df$total < 30, "a", ifelse(df$total >  :    error in evaluating argument 'no' in selecting method function 'ifelse': error in ifelse(df$total > 30, "p") :    argument "no" missing, no default 

you can consider 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 says categorize scores -inf 0 "0", scores between 0 , 30 "f", , scores between 30 , inf "p". thus, if vector of scores c(0, 12, 30, 31, 12, 0, 40), 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 

Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -