代码之家  ›  专栏  ›  技术社区  ›  Alex

将布尔指示符列转换为单因子列

r
  •  4
  • Alex  · 技术社区  · 6 年前

    几年前也有人问过类似的问题 here .

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

    我想做以下工作:

    # 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
    

    创建于2018-10-22 reprex package (v0.2.0)。

    请注意,列名称将作为字符值粘贴到 desired_col . 如果没有值,则该值== none . 如果存在多个值,则用分隔值 , .

    1 回复  |  直到 6 年前
        1
  •  2
  •   MrFlick    6 年前

    下面是使用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的行上运行函数。