Irakli Irakli - 1 month ago 6
R Question

R: how to pass a list of filters to a function

I have a list of custom filters that I need to subset my dataframe by. For example, for mtcars I have this list:

filters=c(mpg>15, wt<2, carb>2 & am==0)


I want to pass this list to a function containing dplyr/pipes

fmean <- function(filter_x) mtcars %>% filter(filter_x) %>% summarise(mean(disp))


My expected output after passing the list to the fmean is:

subset mean(disp)
mpg>15 192
wt<2 80.2
carb>2 & am==0 324


How to obtain the above output?

Answer

data.table way, with eval(parse())

library(data.table)
mt_dt <- data.table(mtcars)

filters <- c("mpg > 15", "wt < 2", "carb > 2 & am==0")

out <- sapply(filters, function(x){mt_dt[eval(parse(text = x)), mean(disp)]})
out
# mpg > 15           wt < 2     carb > 2 & am==0 
# 192.3115          80.2250             324.4600 

We are looping over our filters, and for each filter we subset and apply our aggregation function

This results in a named vector, which is quite flexible to work with. If you prefer a table, you can use:

data.table(subset = names(out), `mean(disp)` = out)
#              subset mean(disp)
# 1:         mpg > 15   192.3115
# 2:           wt < 2    80.2250
# 3: carb > 2 & am==0   324.4600
Comments