Extracting column names with condition from a data frame

后端 未结 6 714
轮回少年
轮回少年 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:56

    Here is another solution.

    x <- apply(df[-1]!=0, 1, function(x) paste(names(df[-1])[x], collapse=","))
    names(x) <- df$ID
    cbind(x)               # or cbind(x[x!=""]) if you want to remove empty strings
    
    #    x      
    # 1  "A1,A2"
    # 2  "A1,A2"
    # 3  "A1"   
    # 4  "A1"   
    # 5  ""     
    # 6  "A2,A8"
    # 7  "A6,A8"
    # 8  "A1,A8"
    # 9  "A6,A8"
    # 10 "A8"   
    # 11 "A1,A8"
    # 12 "A6"   
    # 13 "A5,A8"
    # 14 ""     
    # 15 "A8"   
    # 16 "A8"   
    # 17 "A8"   
    # 18 "A8"   
    # 19 "A8"   
    # 20 "A8"   
    # 21 "A7"   
    # 22 "" 
    

提交回复
热议问题