Extracting column names with condition from a data frame

后端 未结 6 716
轮回少年
轮回少年 2021-01-18 05:12
dput(new)
structure(list(ID = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 
13, 14, 15, 16, 17, 18, 19, 20, 21, 22), A1 = c(1, 1, 1, 1, 0, 
0, 0, 1, 0, 0, 1, 0, 0, 0, 0,         


        
6条回答
  •  北荒
    北荒 (楼主)
    2021-01-18 05:51

    We can get the data in long format, filter rows where value is not 0, group_by ID and create a comma-separated value of each column name.

    library(dplyr)
    
    new %>%
      tidyr::pivot_longer(cols = -ID) %>%
      filter(value != 0) %>%
      group_by(ID) %>%
      summarise(name = toString(name))
    
    # A tibble: 19 x 2
    #      ID name  
    #     
    # 1     1 A1, A2
    # 2     2 A1, A2
    # 3     3 A1    
    # 4     4 A1    
    # 5     6 A2, A8
    # 6     7 A6, A8
    # 7     8 A1, A8
    # 8     9 A6, A8
    # 9    10 A8    
    #10    11 A1, A8
    #.....
    

提交回复
热议问题