r - 如何创建新列并通过 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
用于选择索引,但无法弄清楚。谁能帮我?
解决方案
我们可以使用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)
推荐阅读
- python - 在 Python 中,我有一个字典,如何在第一个索引上添加一个新键?
- sql - 重命名列 MySQL Workbench MariaDB
- javascript - 需要使用 event.currentTarget 进行 Javascript 计算方面的帮助
- javascript - 从 Fullcalendar 向 PHP 传递参数
- mysql - 连接两个几乎相同的没有空值的 sql 结果行
- swift - swift SceneKit 对象为空
- python - 如何过滤列和绘制一堆文件
- azure - 如何在 ARM 模板中获取 AzureAD 用户 principalId
- android - 当应用程序获得焦点时,何时检查 Android API 29 中的剪贴板内容?
- android - MPAndroidChart - 比例线图