1

I am trying to merge columns into one column, I've combined them using pmap.

Some columns have NAs, I'd like to remove the NAs from the combined column col_comb and leave the other values.

df = tribble(~id, ~col1, ~col2, ~col3,
             1, "a", "b", "c",
             2, "a", NA, "c",
             3, "a", NA, NA,
             4, NA, NA, NA)
df = df %>% 
  mutate(col_comb = pmap(list(col1,col2,col3), c)) 

enter image description here

1 Answers1

2

We can specify a lambda function to do this

library(dplyr)
library(purrr)
df1 <- df %>% 
    mutate(col_comb = pmap(select(., starts_with('col')), 
             ~  as.character(na.omit(c(...)))))

-output

df1$col_comb
#[[1]]
#[1] "a" "b" "c"

#[[2]]
#[1] "a" "c"

#[[3]]
#[1] "a"

#[[4]]
#character(0)

Or another option is c_across with rowwise

df %>% 
  rowwise %>% 
  mutate(col_comb = list(na.omit(c_across(-id)))) %>% 
  ungroup
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Thank you! .. You know what, I was waiting for you when I wrote this and I was sure you will answer it :) That works perfectly, and I can apply list operations `length`, `first`, etc. – Mohamed Mostafa El-Sayyad Mar 24 '21 at 15:55