对于简单的数据框:
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))
我想写一些基于男性和女性得分的if语句。基本的if函数将如下所示:
df$score3<-ifelse(df$score <45,"low",
ifelse(df$score>=45 & df$score<55,"normal",
ifelse(df$score >=55,"high", NA)))
我如何仅为男性更改此表达式(单独的截止将用于女性(例如,低=&lt; 50,正常=&gt; = 50&amp;&lt; 58,高=&gt; = 58))。
如果可以根据数据框中的其他列使用if语句给出任何建议,我将非常感激。
答案 0 :(得分:4)
使用数据结构来表示您的标准
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