我有3列,其中包括指标(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))
我想返回一个字符列“ qualifiers”,以使指示符== 1的列名称串联在一个字符串中,如下所示:
*qualifiers*
integrated_intervention
delivery_group
delivery_group, culturally_tailored
culturally_tailored
我尝试了extdplyr :: ind(具有各种选项),但没有成功。下面的一个崩溃了我的R会话。
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)
我找到了Convert Boolean indicator columns to a single factor column,但认为可能会有一个更简单的解决方案。
答案 0 :(得分:2)
您可以尝试:
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
或者,如莫里斯所建议的那样紧凑:
apply(icols, 1, function(x) toString(names(icols)[x == 1]))
答案 1 :(得分:1)
答案 2 :(得分:0)
这是一种疯狂的方式:
library(tidyverse)
icols %>%
mutate(qualifiers = case_when(
delivery_group & culturally_tailored == 1 ~ "delivery_group, culturally_tailored",
delivery_group & integrated_intervention == 1 ~ "delivery_group, integrated_intervation",
culturally_tailored & integrated_intervention == 1 ~ "culturally_tailored, integrated_intervation",
culturally_tailored == 1 ~ "culturally_tailored",
integrated_intervention == 1 ~ "integrated_intervention",
delivery_group == 1 ~ "delivery_group"))
# A tibble: 5 x 4
delivery_group culturally_tailored integrated_intervention qualifiers
<dbl> <dbl> <dbl> <chr>
1 0 0 1 integrated_intervention
2 1 0 0 delivery_group
3 1 1 0 delivery_group, culturally_tailored
4 0 0 0 NA
5 0 1 0 culturally_tailored