简体   繁体   中英

If statements based on another column within a dataframe: in R

For a simple dataframe:

df <- structure(list(id = 1:9, sex = structure(c(2L, 2L, 1L, 2L, 1L, 
                                              1L, 2L, 2L, 1L), .Label = c("f", "m"), class = "factor"), score = c(55L, 
                                                                                                                  60L, 62L, 47L, 45L, 52L, 41L, 46L, 57L)), .Names = c("id", "sex", 
                                                                                                                                                                       "score"), class = "data.frame", row.names = c(NA, -9L))

I want to write some if statements based on score for males and females. The basic if function would go like this:

df$score3<-ifelse(df$score <45,"low",     
                         ifelse(df$score>=45 & df$score<55,"normal",
                                ifelse(df$score >=55,"high", NA)))

How would I change this expression for males only (separate cut offs will be used for females (say low = <50, normal = >=50 & <58, high = >=58)).

If any advice could be given on using if statements based on another column within a dataframe, I would be most grateful.

Use a data structure to represent your criteria

criteria<-list(m=c(0,50,58),f=c(0,45,55))
labels<-c("low","normal","high")
grade<-function(score,sex) labels[findInterval(score,criteria[[sex]])]

df$grade<-mapply(grade,df$score,as.character(df$sex))
id sex score  grade
1  1   m    55 normal
2  2   m    60   high
3  3   f    62   high
4  4   m    47    low
5  5   f    45 normal
6  6   f    52 normal
7  7   m    41    low
8  8   m    46    low
9  9   f    57   high

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.

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