Home > Net >  Create new column based on values from three other columns in R
Create new column based on values from three other columns in R

Time:05-09

I have a dataframe:

df <- data.frame('a'=c(1,NA,3,NA,NA), 'b'=c(NA,NA,NA,4,50), 'c'=c(NA,5,NA,NA,NA))
df
   a  b  c
1  1 NA NA
2 NA NA  5
3  3 NA NA
4 NA  4 NA
5 NA 50 NA

I need to create a new column d that combines only the values without the NAs:

  a  b  c  d
1  1 NA NA 1
2 NA NA  5 5
3  3 NA NA 3
4 NA  4 NA 4
5 NA 50 NA 50

CodePudding user response:

Additional to the solution by @r2evans in the comment section:

We could use coalesce from dplyr package:

df %>% 
  mutate(d = coalesce(a, b, c))
   a  b  c  d
1  1 NA NA  1
2 NA NA  5  5
3  3 NA NA  3
4 NA  4 NA  4
5 NA 50 NA 50

OR

We could use unite from tidyr package with na.rm argument:

library(tidyr)
library(dplyr)

df %>% 
  unite(d, a:c, na.rm = TRUE, remove = FALSE)
   d  a  b  c
1  1  1 NA NA
2  5 NA NA  5
3  3  3 NA NA
4  4 NA  4 NA
5 50 NA 50 NA
  •  Tags:  
  • r
  • Related