jeudi 14 juillet 2016

How to create new column with all non-NA values from multiple other columns?

I would like to create a column d, which includes all the non-NA values from the other columns.

I tried ifelse, but cannot figure out how to make it nested in the proper manner, so that the value in column c is included as well.. Perhaps something else than ifelse should be used?

Here is a "dummy" dataframe:

 a <- c(NA, NA, NA, 1, 2, 2, NA, NA)
 b <- c(2, 3, 6, NA, NA, NA, NA, NA)
 c <- c(NA, NA, NA, NA, NA, NA, 3, NA)
 data <- data.frame(a, b, c)

 data$d <- ifelse(is.na(data$a), data$b, data$a)

Aucun commentaire:

Enregistrer un commentaire