Easily done with coalesce
from dplyr
. This solution works for N number of columns:
library(dplyr)
data %>%
mutate(col4 = coalesce(!!!data[-1]))
Result:
id col1 col2 col3 col4
1 1 10 NA NA 10
2 2 NA 12 NA 12
3 3 NA NA 13 13
4 4 NA NA 1 1
5 5 2 3 NA 2
Data:
data = read.table(text = "id col1 col2 col3
1 10 NA NA
2 NA 12 NA
3 NA NA 13
4 NA NA 1
5 2 3 NA", header = T)
Notes:
!!!
shouldn't be confused with the negation operator !
(understandable confusion). It is an operator that is part of rlang
, or the tidyverse
(also available to dplyr
) which enables explicit splicing.
What this means is that instead of inputting the entire data frame into coalesce
(coalesce(data[-1])
), I am separating the columns of data[-1]
(or elements of the list) and have each element as an input to coalesce
. So this:
coalesce(!!!data[-1])
is actually equivalent to this:
coalesce(col1, col2, col3)
The advantage of writing it this way is that you don't have to know the column names nor how many columns there are to begin with.