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,
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