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

how do i combine 3 columns into 2 columns in R?

I am trying to take 3 columns and combine them into 2 columns. For each row, only two of the three columns have string data (the third contains NA). My first thought was to use coalesce but I can’t get it to work for my case.

tibble(
  col1 = c(NA, 1, 0),
  col2 = c(1, NA, 1),
  col3 = c(0, 1, NA)
)

# A tibble: 3 × 3
  coder1 coder2 coder3
   <dbl>  <dbl>  <dbl>
1     NA      1      0
2      1     NA      1
3      0      1     NA

My desired output would be like this:

tibble(
  col1 = c(NA, 1, 0),
  col2 = c(1, NA, 1),
  col3 = c(0, 1, NA)
  out1 = c(1, 1, 0),
  out2 = c(0, 1, 1)
)

# A tibble: 3 × 5
  coder1 coder2 coder3 test1 test2
   <dbl>  <dbl>  <dbl> <dbl> <dbl>
1     NA      1      0     1     0
2      1     NA      1     1     1
3      0      1     NA     0     1

This is my first stackoverflow question, so please let me know if I can request help more clearly! Thanks in advance.

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 :

One quick way:

df %>%
  rowwise() %>%
  mutate(test=list(na.omit(c_across(everything()))))%>%
  unnest_wider(test, names_sep = '')

  col1  col2  col3 test1 test2
  <dbl> <dbl> <dbl> <dbl> <dbl>
1    NA     1     0     1     0
2     1    NA     1     1     1
3     0     1    NA     0     1

in Base R:

cbind(df, test=t(unstack(na.omit(stack(data.frame(t(df)))))))
   col1 col2 col3 test.1 test.2
X1   NA    1    0      1      0
X2    1   NA    1      1      1
X3    0    1   NA      0      1
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