Search code examples
rdata.table

extracting the required columns from a data.table with given conditions


This is my dataset.

DTmtcars = as.data.table(mtcars); DTmtcars[, mtcarsname := rownames(mtcars)];

And these are the user input and can vary, at least 1 will be always available which can be in any order, these user inputs are just telling the column names of the data.table DTmtcars.

It is a sample for this question.

column1="mtcarsname";
column2="am";
column3="gear";
column4=NA;

requirement is display these columns of the dataset.

The code is an ideal solution for the sample user input above.

DTmtcars[, .(w,x,y) , env =  list(w=column1, x = column2,y =column3,z = column4)]

probably an ifelse/fifelse or any thing else to make this code dynamic so that the output is produced for all possible combinations of user input.

Output should be data.table and not a vector or concat. code should be efficient and can be applied on a very large dataset. I would appreciate if it can be done using data.table package only.


Solution

  • As it seems you do not want the NA column out here is my try

    library(data.table)
    DTmtcars = as.data.table(mtcars); DTmtcars[, mtcarsname := rownames(mtcars)];
    column1="mtcarsname";
    column2="am";
    column3="gear";
    column4=NA;
    
    DTmtcars[,.SD, .SDcols = na.omit(c(column1,column2,column3,column4))]
    

    Which leads to

                 mtcarsname    am  gear
                     <char> <num> <num>
     1:           Mazda RX4     1     4
     2:       Mazda RX4 Wag     1     4
     3:          Datsun 710     1     4
     4:      Hornet 4 Drive     0     3
     5:   Hornet Sportabout     0     3
     6:             Valiant     0     3
     7:          Duster 360     0     3
     8:           Merc 240D     0     4
     9:            Merc 230     0     4
    10:            Merc 280     0     4
    11:           Merc 280C     0     4
                 ....