首页 > 解决方案 > 将布尔指标列转换为单因子列

问题描述

几年前在这里问过类似的问题。

我的设置有点不同。我的指标变量不是“真正的”虚拟变量,因为它们重叠。

我想做以下事情:

# fake data
library(tibble)
dat <- tribble(
  ~"a", ~"b", ~"c",
  0,  0,   0,
  1, 0, 0,
  1, 1, 1
)
dat
#> # A tibble: 3 x 3
#>       a     b     c
#>   <dbl> <dbl> <dbl>
#> 1     0     0     0
#> 2     1     0     0
#> 3     1     1     1

# desired data
desired_col <- c("none", "a", "a,b,c")
cbind(dat, desired_col)
#>   a b c desired_col
#> 1 0 0 0        none
#> 2 1 0 0           a
#> 3 1 1 1       a,b,c

reprex 包(v0.2.0)于 2018 年 10 月 22 日创建。

请注意,列名将作为字符值粘贴到desired_col. 如果不存在值,则值 == none。如果存在多个值,则这些值用 分隔,

标签: r

解决方案


这是使用 tidyverse 函数的一种方法

library(tibble)
library(dplyr)
library(tidyr)
dat %>% 
  rowid_to_column() %>% # keep data for each row together
  gather("col", "val", -rowid) %>% 
  mutate(rowid=factor(rowid)) %>% 
  filter(val==1) %>% 
  group_by(rowid) %>% 
  summarize(desired=paste(col, collapse=",")) %>%  #collapse values
  complete(rowid, fill = list(desired="none")) # add "none" for empty groups

#   rowid desired
#   <fct> <chr>  
# 1 1     none   
# 2 2     a      
# 3 3     a,b,c  

基本思想涉及重塑数据,以便我们可以运行组函数,而不是在 data.frame 的行上运行函数,这并不容易。


推荐阅读