lundi 13 juin 2016

Ifelse statement with nested data.table statements

This is my data frame.

library(data.table)
     dt <- fread('
 Name     Video   Webinar Meeting Conference  Level  NextStep
  John       1         0        0       0      1     Webinar,Meeting,Conference
  John       1         1        0       0      1     Meeting,Conference
  John       1         1        1       0      2     Conference      
  Tom        0         0        1       0      1     Webinar,Conference,Video
  Tom        0         0        1       1      2     Webinar,Video   
  Kyle       0         0        0       1      2     Webinar,Meeting,Video

                                ')

I am creating the nextstep column by doing this

dt[, nextstep := paste0(names(.SD)[.SD==0], collapse = ','), 1:nrow(DT), .SDcols = 2:5][]

according to the solution here Making a character string with column names with zero values

Now I want to change the order of how the elements show up in the next step column based on the 'Level' field. For example, if it is level 1, I want conference to show up before Webinar & Meeting. If level 2, I want video to always show up last.This is my attempt.

 dt<-dt[, NextStep := ifelse(Level1=="Level0",
(paste0(names(.SD)[.SD==0], collapse = ';'), 1:nrow(dt), .SDcols = c(5,2,3,4)),
      ifelse(EngagementLevel1=="Level2",
(paste0(names(.SD)[.SD==0], collapse = ';'), 1:nrow(dt), .SDcols = c(3,4,5,2))))]

I am just trying to reorder the elements within 'nextstep' field based on the 'Level' field. Sincerely appreciate your help!

Aucun commentaire:

Enregistrer un commentaire