data.table - How to create dynamic query in data table in R -


updated example: have function follows:

myfun <- function(dt, var){     for(i in 1:length(var)){     s = substitute(!(is.na(x) | is.nan(x)), list(x=as.symbol(eval(var[i]))))     dt = dt[eval(s)]   }   return(dt) } 

input:

> dt = data.table(id=c(1,2,3,4,5), x=c(1,2,na,4,5), y=c(1,na,3,4,na)) > dt    id  x  y 1:  1  1  1 2:  2  2 na 3:  3 na  3 4:  4  4  4 5:  5  5 na 

runs:

> myfun(dt, var=c("x", "y"))    id x y 1:  1 1 1 2:  4 4 4 > myfun(dt, var=c("x"))    id x  y 1:  1 1  1 2:  2 2 na 3:  4 4  4 4:  5 5 na 

var character array of variables in dt. goal obtain rows in dt not have na or nan wrt of variables in var.

i not want loop. want construct query s conditions , evaluate query dt. first case want:

s = !(is.na(x) | is.nan(x) | is.na(y) | is.nan(y)) 

and second case want:

s = !(is.na(x) | is.nan(x)) 

how can construct dynamic query s , run once i/where query in data table.

more how can create dynamic expression based on input. using expression(paste()) did not me. can use substitute.

ans:

var = c("x","y") str=paste0("is.na(",var,") |", " is.nan(",var,")", collapse="|") s = parse(text=paste("!(",str,")")) dt[eval(s)] 

source: how use unknown number of key columns in data.table


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

mysql - Pass value between different pages (form) with PHP -