We can grouo by the rows, unlist
the Subset of Data.table (.SD
), subset the names of the dataset, paste
the elements together and assign (:=
) to 'newCol'
nm1 <- names(dt)[-4]
dt[, newCol := toString(nm1[unlist(.SD)]) ,by = 1:nrow(dt),.SDcols = nm1]
Or another option is melt
to 'long' format and then do a join
dt[melt(dt[, n := seq_len(.N)], id.var = c("n", "PASTE"))[,
toString(variable[value]), n], on = "n"]