r - New column based on present values from other columns -
i create data-frame column based on whether of other columns have present values.
example: column c created depending on whether there present values in rest of row.
age bmi hyp chl c 1 1 na na na na 2 2 22.7 1 187 1 3 1 na 1 187 1 4 3 na na na na 5 1 20.4 1 113 1 6 3 na na 184 1 7 1 22.5 1 118 1 8 1 30.1 1 187 1 9 2 22.0 1 238 1 10 2 na na na na 11 1 na na na na 12 2 na na na na 13 3 21.7 1 206 1 14 2 28.7 2 204 1 15 1 29.6 1 na 1 16 1 na na na na 17 3 27.2 2 284 1 18 2 26.3 2 199 1 19 1 35.3 1 218 1 20 3 25.5 2 na 1 21 1 na na na na 22 1 33.2 1 229 1 23 1 27.5 1 131 1 24 3 24.9 1 na 1 25 2 27.4 1 186 1 column c created using following bit of code:
df <- transform(df, c=ifelse(!(is.na(bmi)) | !(is.na(hyp)) | !(is.na(chl)),1,na)) my question is: how can create function above without specifying columns. ie if have dataset 45 columns, don't want name of them in ifelse statement.
many in advance.
we can use rowsums on logical matrix , convert vector of na , 1
df$c <- na^!rowsums(!is.na(df[-1])) df$c #[1] na 1 1 na 1 1 1 1 1 na na na 1 1 1 na 1 1 1 1 na 1 1 1 1
Comments
Post a Comment