对于一个简单的数据框:
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)))
我如何仅针对男性更改此表达式(针对女性将使用单独的截止值(例如低 = <50,正常 = >=50 & <58,高 = >=58))。
如果可以就使用基于数据框中另一列的 if 语句提供任何建议,我将不胜感激。
最佳答案
使用数据结构来表示您的标准
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
关于r - If 语句基于数据帧中的另一列 : in R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35229671/