Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store filter expressions as strings?

For the analysis of a species database, I often need to change lots of criteria, depending on the projects scope etc.

As it is very inconvenient to always change the criteria within the main script itself, I started defining various parameters as variables in an exterior parameters.R file which will be copied to the project specific folders and adjusted there, and which will be sourced from the main.R file.

This work great, but now that I come to filter expressions, I can't find a way to store them as a string in my parameters file.

The standard filter expression will be this one:

 rlb == "1" | rlb == "2" | rlb== "3" | rlb == "G" | rlb == "R" | rld ==
 "1" | rld == "2" | rld== "3" | rld == "G" | rld == "R" | ffh2 > 1 | ffh4
 == 1 | ffh5 == 1 | spa1 == 1 | sap == 1

Due to the "" in some of the parameters, I can't assign it as a string variable, cause R is complaining that there are unknown tokens or objects.

How can I assign this filter expression to a variable, so I can use it later e.g. with eval(my_filter_variable) etc to perform my filtering?

like image 613
Bernd V. Avatar asked Mar 05 '23 14:03

Bernd V.


1 Answers

In addition to @Konrad's methods, if the expression is a string, then we can use parse_expr from rlang

library(rlang)
library(dplyr)
df1 %>% 
    filter(!! parse_expr(expr1))
#   col_A col_B
#1     A     1

data

 df1 <- data.frame(col_A = LETTERS[1:10],
           col_B = 1:10,
           stringsAsFactors = FALSE)

expr1 <-  "col_A == 'A' & col_B == 1"
like image 189
akrun Avatar answered Mar 15 '23 02:03

akrun