Create a new column with non-null columns' names

前端 未结 4 1108
醉话见心
醉话见心 2020-12-11 06:16

My data set looks like this one:

library(data.table)

df <- data.table(a = c(1,2,3,4,5),
                 b = c(1,0,2,5,1),
                 c = c(0,1,1,         


        
4条回答
  •  自闭症患者
    2020-12-11 06:27

    This can be a bit lengthy.

    For every row finding a column whose value is not 0 and then pasting the column names together.

    data.table(a= df$a, z = lapply(apply(df, 1, 
               function(x) which(x[-1]!= 0)), 
               function(x) paste0(names(x), collapse = "_")))
    
    
    #   a   z
    #1: 1 b_d
    #2: 2   c
    #3: 3 b_c
    #4: 4 b_d
    #5: 5 b_d
    

提交回复
热议问题