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.
>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