我有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))
我想返回单个字符列'限定符',这样带有指示符== 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,但认为可能有一个更简单的解决方案。
你可以试试:
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建议的那样:
apply(icols, 1, function(x) toString(names(icols)[x == 1]))
我不确定这是一个“简单”的解决方案,但这是一个使用tidyverse的解决方案。
library(tidyverse)
icols <- tibble(
delivery_group = c(0, 1, 1, 0, 0),
culturally_tailored = c(0, 0, 1, 0, 1),
integrated_intervention = c(1, 0, 0, 0, 0)
)
icols %>%
rowid_to_column(var = "rowid") %>%
gather(key = "qualifiers", value = "indicator", -rowid) %>%
filter(indicator == 1) %>%
group_by(rowid) %>%
summarize(qualifiers = paste(qualifiers, collapse = ", ")) %>%
ungroup() %>%
complete(rowid = 1:nrow(icols)) %>%
select(qualifiers)
#> # A tibble: 5 x 1
#> qualifiers
#> <chr>
#> 1 integrated_intervention
#> 2 delivery_group
#> 3 delivery_group, culturally_tailored
#> 4 <NA>
#> 5 culturally_tailored
由reprex package创建于2019-02-27(v0.2.1)
这是一个疯狂的方式:
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