如何创建新列并通过r中的选定行添加列名

问题描述 投票:0回答:1
a<-c(TRUE,FALSE,TRUE,FALSE,TRUE,FALSE)
b<-c(TRUE,FALSE,TRUE,FALSE,FALSE,FALSE)
c<-c(TRUE,TRUE,TRUE,FALSE,TRUE,FALSE)
custumer<-c("one","two","three","four","five","six")
df<-data.frame(custumer,a,b,c)

这是示例代码。看起来像这样:

  custumer     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列,并在每个真实的数据列中仅添加名称。

  custumer     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

我没有使用应用功能或用于选择索引bu的巫婆,但没有弄清楚。有人可以帮助我吗?

对不起,英语不好:/

r dataframe dplyr data-manipulation data-wrangling
1个回答
0
投票
df$items = apply(df[2:4], 1, function(x) toString(names(df[2:4])[x]))
df
#   custumer     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    a, c
# 6      six FALSE FALSE FALSE       

0
投票
df$items <- apply(df, 1, function(x) toString(names(df)[which(x == TRUE)]))
© www.soinside.com 2019 - 2024. All rights reserved.