I would like to create a data-frame column based on whether any of the other columns have any present values.
Example: column c was created depending on whether there are any present values in the rest of the 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 was created using the 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 I create a function that does the above without specifying the columns. Ie if I have a dataset with 45 columns, I don't want to name all of them in the ifelse statement.
Many thanks in advance.
We can use rowSums
on a logical matrix and then convert it to a vector
of NA and 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
We can also use the coalesce
function from the dplyr
package.
dt2 <- dt %>%
mutate_all(funs(as.numeric(.))) %>%
mutate(c = coalesce(.$bmi, .$hyp, .$chl)) %>%
mutate(c = ifelse(!is.na(c), 1, c))
dt2
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
DATA
dt <- read.table(text = " age bmi hyp chl
1 1 NA NA NA
2 2 22.7 1 187
3 1 NA 1 187
4 3 NA NA NA
5 1 20.4 1 113
6 3 NA NA 184
7 1 22.5 1 118
8 1 30.1 1 187
9 2 22.0 1 238
10 2 NA NA NA
11 1 NA NA NA
12 2 NA NA NA
13 3 21.7 1 206
14 2 28.7 2 204
15 1 29.6 1 NA
16 1 NA NA NA
17 3 27.2 2 284
18 2 26.3 2 199
19 1 35.3 1 218
20 3 25.5 2 NA
21 1 NA NA NA
22 1 33.2 1 229
23 1 27.5 1 131
24 3 24.9 1 NA
25 2 27.4 1 186",
header = TRUE, stringsAsFactors = FALSE)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.