Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 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 Reply

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...