惰性评估参数中的参数

Parameter in the argument for lazy evaluation

我正在尝试将变量表达式传递给惰性求值函数:

test <- function(expr){
  tmp <- iris[eval(substitute(expr), iris), ]
  #actually do and return complicated stuff with tmp
  return(data.frame(n = nrow(tmp), sepal.length = mean(tmp$Sepal.Length)))
}

test.species <- function(species){
  return(test(Species == substitute(species)))
}

#usage:
test.species("virginica")

功能测试正常。但为什么 test.species 不起作用?

substitute(Species == substitute(species))test 内部求值,这意味着 Species 不是与字符值进行比较,而是与符号 (substitute(species)) 进行比较。

这里可以用

bquote代替:

test.species <- function(species){
  eval(bquote(test(Species == .(species))))
}
test.species("virginica")
#   n sepal.length
#1 50        6.588