Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading