是否有允许您在命令中插入变量的 R 函数?

Is there a R function that allows you to insert a variable inside a command?

例如: 假设我有一个名为“cors”的对象,它只包含一个字符串(例如“Spain”)。我希望在下面的表达式 (1) 中将“cors”替换为“西班牙”,从而得到表达式 (2):

#(1)
DF <- DF %>% filter(str_detect(Country, "Germany|cors", negate = TRUE))
#(2)
DF <- DF %>% filter(str_detect(Country, "Germany|Spain", negate = TRUE))

P.S:我知道在 MATLAB 中这可以用“eval()”命令处理,但在 R 中它显然具有完全不同的适用性。

如果我们有对象,则将其放在 quotes 之外并使用 paste/str_c 创建字符串

library(dplyr)
library(stringr)
cors <- "Spain"
pat <- str_c(c("Germany", cors),  collapse = "|")
DF %>%
    filter(str_detect(Country, pat, negate = TRUE))

或者另一种选择是使用 glue 进行字符串插值(假设 cors 对象只有一个字符串元素)

DF %>%
    filter(str_detect(Country, glue::glue("Germany|{cors}"), negate = TRUE))

或者这可以在 base R 中用 grepl

完成
pat <- paste(c("Germany", cors), collapse = "|")
subset(DF, !grepl(pat, Country))

如果你真的想要eval,你可以这样做:

cors <- 'Spain'

DF <- DF %>% filter(
  eval(
    parse(text=paste0('str_detect(Country, "Germany|', cors, '", negate=TRUE)'))
  ))