如何将指标列转换为串联列(列名) [英] How to convert indicator columns to a concatenated column (of column names)
本文介绍了如何将指标列转换为串联列(列名)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 3 列由指标 (0/1) 组成
I have 3 columns consisting of indicator (0/1)
icols <-
structure(list(delivery_group = c(0, 1, 1, 0, 0), culturally_tailored = c(0,
0, 1, 0, 1), integrated_intervention = c(1, 0, 0, 0, 0)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -5L))
我想返回一个单字符列限定符",这样带有指示符 == 1 的列名将连接在一个字符串中,如下所示:
I would like to return a single character column 'qualifiers', such that column names with indicator == 1 are concatenated in a string as below:
*qualifiers*
integrated_intervention
delivery_group
delivery_group, culturally_tailored
culturally_tailored
我尝试了 extdplyr::ind(带有各种选项)但没有成功.下面的一个崩溃了我的 R 会话.
I tried extdplyr::ind (with various options) without success. The one below crashed my R session.
icols <- extdplyr::ind_to_char(col = qualifiers, ret_factor = FALSE, remove = TRUE,
from = c("delivery_group", "culturally_tailored", "integrated_intervention"),
mutually_exclusive = FALSE, collectively_exhaustive = FALSE)
我发现 将布尔指标列转换为单因子列,但认为可能有更简单的解决方案.
I found Convert Boolean indicator columns to a single factor column, but thought there might be a simpler solution.
推荐答案
你可以试试:
icols$collapsed <- apply(icols, 1, function(x) paste0(names(icols)[x == 1], collapse = ", "))
icols
delivery_group culturally_tailored integrated_intervention collapsed
1 0 0 1 integrated_intervention
2 1 0 0 delivery_group
3 1 1 0 delivery_group, culturally_tailored
4 0 0 0
5 0 1 0 culturally_tailored
或者,更像 Maurits 建议的那样:
Or, even more compactly as Maurits suggested:
apply(icols, 1, function(x) toString(names(icols)[x == 1]))
这篇关于如何将指标列转换为串联列(列名)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文