Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter data table by dynamic column name

lets say I have a data.table with columns A, B and C

I'd like to write a function that applies a filter (for example A>1) but "A" needs to be dynamic (the function's parameter) so if I inform A, it does A>1; If I inform B, it does B>1 and so on... (A and B always being the columns names, of course)

Example: Lets say my data is bellow, I'd like to do "A==1" and it would return the green line, or do "B==1 & C==1" and return the blue line.

enter image description here

Can this be done? thanks

like image 360
Diego Avatar asked Apr 10 '15 14:04

Diego


1 Answers

You can try

f1 <- function(dat, colName){dat[eval(as.name(colName))>1]}
setDT(df1)
f1(df1, 'A')
f1(df1, 'B')

If you need to make the value also dynamic

f2 <- function(dat, colName, value){dat[eval(as.name(colName))>value]}
f2(df1, 'A', 1)
f2(df1, 'A', 5)

data

set.seed(24)
df1 <- data.frame(A=sample(-5:10, 20, replace=TRUE), 
      B=rnorm(20), C=LETTERS[1:20], stringsAsFactors=FALSE) 
like image 193
akrun Avatar answered Sep 30 '22 05:09

akrun