If statements based on another column within a dataframe: in R -
for 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 write if statements based on score males , females. basic if function go this:
df$score3<-ifelse(df$score <45,"low", ifelse(df$score>=45 & df$score<55,"normal", ifelse(df$score >=55,"high", na)))
how change expression males (separate cut offs used females (say low = <50, normal = >=50 & <58, high = >=58)).
if advice given on using if statements based on column within dataframe, grateful.
use data structure represent 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
Comments
Post a Comment