R: Add column with condition-check on three columns? -
my df1 follows:
df1 <- data.frame(a=c("a","b","c","d","e"), b=c("f","g","t","g","u"), c=c("m","na","na","na","m"), d=c("a","na","na","na","na"), e=c("na","na","na","na","g"), g=c(1:5)) b c d e g 1 f m na 1 2 b g na na na 2 3 c t na na na 3 4 d g na na na 4 5 e u m na g 5 i want add column based on readings in column c, d , e. if na, want add x column h. if of them not na, want add yes column h. results follows:
b c d e g h 1 f m na 1 yes 2 b g na na na 2 x 3 c t na na na 3 x 4 d g na na na 4 x 5 e u m na g 5 yes could experts teach me how efficiently r?
transform(df1, h = ifelse(is.na(c) & is.na(d) & is.na(e), "x", "yes")) note works if nas encoded na rather string "na".
see ?transform , ?ifelse descriptions of functions. single & operator pairs vector operands item item , boolean operation on each pair, returning logical vector.
Comments
Post a Comment