根据 R 中的值将多列折叠为一列

问题描述 投票:0回答:1

我有

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')

如何用列名称替换每列中的所有“1”,然后将该列折叠成一个新列?预期结果是

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')

我在这里找到了第二步(r将多列数据折叠成一列),但我还没有完全做到这一点。

r dataframe function merge multiple-columns
1个回答
0
投票

这是使用

tidyverse
transmute
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
© www.soinside.com 2019 - 2024. All rights reserved.