Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variables to subset a data.table

Tags:

r

data.table

scratching my head on this one. Suppose I am exploring the cars dataset

data(mtcars)
test_dt <- as.data.table(mtcars)

I can easily subset the table using something like this:

new_dt <- test_dt[cyl == '4', c('disp', 'hp', 'gear')]

I get 11 rows of data. Now suppose I want to create a function wherein I pass the name of the column to filter along with the value of the filter so I can create any combination of data I want. Something like this:

foo <- function(colToFilter, filterValue) {
  new_dt <- test_dt[colToFilter == filterValue, c('disp', 'hp', 'gear')]
  return(new_dt)
}

and call it like so:

new_dt <- foo('cyl', '4')

The function does not throw an error but returns 0 rows. How can I fix my function so I can return 11 rows like before? TIA

like image 999
ds_practicioner Avatar asked May 19 '17 22:05

ds_practicioner


1 Answers

In order to make your function work, it should be like this:

foo <- function(colToFilter, filterValue) {
 #you need get in order to 'get' the column named cyl
 new_dt <- test_dt[get(colToFilter) == filterValue, list(disp, hp, gear)]
 return(new_dt)
}

Out:

 > foo('cyl', '4')
     disp  hp gear
 1: 108.0  93    4
 2: 146.7  62    4
 3: 140.8  95    4
 4:  78.7  66    4
 5:  75.7  52    4
 6:  71.1  65    4
 7: 120.1  97    3
 8:  79.0  66    4
 9: 120.3  91    5
10:  95.1 113    5
11: 121.0 109    4
like image 108
LyzandeR Avatar answered Oct 23 '22 04:10

LyzandeR