首页 > 解决方案 > 如何创建新列并通过 r 中的选定行添加列名

问题描述

a<-c(TRUE,FALSE,TRUE,FALSE,TRUE,FALSE)
b<-c(TRUE,FALSE,TRUE,FALSE,FALSE,FALSE)
c<-c(TRUE,TRUE,TRUE,FALSE,TRUE,FALSE)
costumer<-c("one","two","three","four","five","six")
df<-data.frame(costumer,a,b,c)

这是一个示例代码。它看起来像这样打印:

  costumer     a     b     c 
1      one  TRUE  TRUE  TRUE  
2      two FALSE FALSE  TRUE 
3    three  TRUE  TRUE  TRUE 
4     four FALSE FALSE FALSE 
5     five  TRUE FALSE  TRUE 
6      six FALSE FALSE FALSE

我想创建一个新列 df$items ,其中仅包含TRUE数据中每一行的列名。像这样的东西:

  costumer     a     b     c items
1      one  TRUE  TRUE  TRUE  a,b,c
2      two FALSE FALSE  TRUE  c
3    three  TRUE  TRUE  TRUE  a,b,c
4     four FALSE FALSE FALSE 
5     five  TRUE FALSE  TRUE 
6      six FALSE FALSE FALSE

我想过使用应用功能或which用于选择索引,但无法弄清楚。谁能帮我?

标签: rdataframedplyrdata-manipulationdata-wrangling

解决方案


我们可以使用pivot_longer重塑为“长”格式,然后按paste

library(dplyr)
library(tidyr)
library(stringr)
df %>%
    pivot_longer(cols = a:c) %>%
    group_by(costumer) %>% 
    summarise(items = toString(name[value])) %>% 
    left_join(df)

推荐阅读