This question already has an answer here:

- Merging two columns into one in R 5 answers

I have two columns of data consisting number and NA entries. There is no row in which both columns have NA as that row's entry, but the columns both have NA as entries for some rows. I would like to make a new vector. If one of my two initial columns has a numerical value, I would like the new vector's entry for that row to be that numerical value. So going from this:

`c1 c2 1 NA 2 NA NA 3 `

to this:

`c1 c2 c3 1 NA 1 2 NA 2 NA 3 3 `

I can do this with for loops:

`for (i in 1:length(c1)) { if (!is.na(c1[i])) { c3[i] <- c1[i] } else { if (!is.na(c2[i])) { c3[i] <- c2[i] } } } `

But I am assuming that there is a cleaner way to do it that takes advantage of R's features. Thank you!

-------------Problems Reply------------

You could use either `pmax/pmin`

`df1$c3 <- do.call(pmax, c(df1, na.rm=TRUE))`

df1

# c1 c2 c3

#1 1 NA 1

#2 2 NA 2

#3 NA 3 3

Or `max.col`

on the logical matrix (`!is.na(df1)`

) to get the column index of maximum value for each row, and `cbind`

with row index (`1:nrow(df1)`

) to extract the elements.

`df1$c3 <- df1[cbind(1:nrow(df1),max.col(!is.na(df1)))]`

###
data

`df1 <- structure(list(c1 = c(1L, 2L, NA), c2 = c(NA, NA, 3L)),`

.Names = c("c1",

"c2"), class = "data.frame", row.names = c(NA, -3L))