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

Collapse multiple columns into one column based on values in R

I have data.frame df1:

 df1 <- data.frame(apple = c('0', '0', '0', '1', '0', '1', '0', '0', '0', '1'),
      banana = c('1', '0', '0', '0', '1', '0', '1', '0', '0', '0'),
      cherry = c('0', '1', '0', '0', '0', '0', '0', '1', '0', '0'),
      date = c('0', '0', '1', '0', '0', '0', '0', '0', '1', '0'))
 rownames(df1) <- c('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten')

How can I substitute all ‘ones’ in each column with the column name and then collapse the column into one new column? Expected result is df2:

 df2 <- data.frame(fruit = c('banana', 'cherry', 'date', 'apple', 'banana', 
      'apple', 'banana', 'cherry', 'date', 'apple'))
 rownames(df2) <- c('one', 'two', 'three', 'four', 'five', 
      'six', 'seven', 'eight', 'nine', 'ten')

I found the second step here (r collapsing data from multiple columns into one) but I don’t quite get there yet.

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 :

Here is tidyverse way using transmute and unite:

library(dplyr)
library(tidyr)

df1 %>%
  transmute(across(apple:date, ~case_when(. == 1 ~ cur_column()), .names = 'new_{col}')) %>% 
  unite(fruit, starts_with('new'), na.rm = TRUE, sep = ' ')
       fruit
one   banana
two   cherry
three   date
four   apple
five  banana
six    apple
seven banana
eight cherry
nine    date
ten    apple
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