The 4th column is my desired column. Video,Webinar,Meeting,Conference are the 4 type of activities that the different customers(names) can engage in. You can see,in a given row,
A possible solution:
DT[, nextstep := paste0(names(.SD)[.SD==0], collapse = ','), 1:nrow(DT), .SDcols = 2:5][]
which gives:
Name Video Webinar Meeting Conference nextstep
1: John 1 0 0 0 Webinar,Meeting,Conference
2: John 1 1 0 0 Meeting,Conference
3: John 1 1 1 0 Conference
4: Tom 0 0 1 0 Video,Webinar,Conference
5: Tom 0 0 1 1 Video,Webinar
6: Kyle 0 0 0 1 Video,Webinar,Meeting
When you want to order the names as you specified in the comments, you can do:
lvls <- c('Webinar', 'Meeting', 'Conference', 'Video')
DT[, nextstep := paste0(lvls[lvls %in% names(.SD)[.SD==0]], collapse = ','),
1:nrow(DT), .SDcols = 2:5][]
which gives:
Name Video Webinar Meeting Conference nextstep
1: John 1 0 0 0 Webinar,Meeting,Conference
2: John 1 1 0 0 Meeting,Conference
3: John 1 1 1 0 Conference
4: Tom 0 0 1 0 Webinar,Conference,Video
5: Tom 0 0 1 1 Webinar,Video
6: Kyle 0 0 0 1 Webinar,Meeting,Video
Instead of using paste0
(with collapse = ','
) you can also use toString
.
Used data:
DT <- fread('Name Video Webinar Meeting Conference
John 1 0 0 0
John 1 1 0 0
John 1 1 1 0
Tom 0 0 1 0
Tom 0 0 1 1
Kyle 0 0 0 1')