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?
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
df1 <- data.frame(col_A = LETTERS[1:10],
col_B = 1:10,
stringsAsFactors = FALSE)
expr1 <- "col_A == 'A' & col_B == 1"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With