Anna Heebøll Anna Heebøll - 1 year ago 100
R Question

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, "A", "B", "A", NA, NA)
b <- c("D", "A", "C", NA, NA, NA, NA, NA)
c <- c(NA, NA, NA, NA, NA, NA, "C", NA)
data <- data.frame(a, b, c)

I would like the d column to look like this:

data$d <- c("D", "A", "C", "A", "B", "A", "C", NA)

Answer Source

Turns out that should've just out in "" and not " " in NA cells.

And if the space is not avoidable use trimws on the column of the dataframe to remove them afterwards:

  data$d <- trimws(data$d)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download