Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

r - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...