【问题标题】:Concatenate binary column names with commas in dplyr在 dplyr 中用逗号连接二进制列名
【发布时间】:2021-09-28 07:49:53
【问题描述】:

我想创建一个新列,使用相应的类别名称来描述给定样本中存在哪些二进制属性。

这是我的数据示例

sample_id type_1 type_2 type_3
1 0 0 1
2 1 1 0
3 1 1 1

理想情况下,我想创建一个 type 列,按名称汇总所有变量,并用逗号分隔

type
type_3
type_1, type_2
type_1, type_2, type_3

我已经尝试使用mutateif_else 来执行此操作,方法是使用字符串名称或零创建额外的三列,但是在连接值时,我会按顺序得到多个逗号,其中有零值。

【问题讨论】:

    标签: r dplyr tidyr


    【解决方案1】:

    这是一个基本的 R 选项 -

    #get columns names that have type in it
    cols <- grep('type', names(df), value = TRUE)
    #get row/column number where 1 is present
    mat <- which(df[cols] == 1, arr.ind = TRUE)
    #For each row combine the column names
    df$type <- tapply(mat[, 2], mat[, 1], function(x) toString(cols[x]))
    df
    
    #  sample_id type_1 type_2 type_3                   type
    #1         1      0      0      1                 type_3
    #2         2      1      1      0         type_1, type_2
    #3         3      1      1      1 type_1, type_2, type_3
    

    【讨论】:

      【解决方案2】:
      library(dplyr)
      
      df <- read.table(text = "sample_id type_1 type_2 type_3
      1 0 0 1
      2 1 1 0
      3 1 1 1", header = TRUE)
      
      df %>% 
        rowwise() %>% 
        mutate(
          type = toString(paste0("type ", which(cur_data()[-1L] == 1)))
        )
      #   sample_id type_1 type_2 type_3 type                  
      #       <int>  <int>  <int>  <int> <chr>                 
      # 1         1      0      0      1 type 3                
      # 2         2      1      1      0 type 1, type 2        
      # 3         3      1      1      1 type 1, type 2, type 3
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-02
        • 1970-01-01
        • 2021-09-05
        • 2012-10-19
        • 1970-01-01
        • 1970-01-01
        • 2011-01-01
        • 1970-01-01
        相关资源
        最近更新 更多