将非标准评估参数传递给子集函数 [英] Passing on non-standard evaluation arguments to the subset function
问题描述
我想在另一个函数中使用 subset
,但要传递来自顶级函数的非标准评估参数.以下是非工作代码,但概述了这个想法:
I want to use subset
within another function but to pass on the non-standard evaluation arguments from the top-level function. The following is non-working code, but outlines the idea:
foo_1 <- function(x, mysubset)
{
# some deparse, substitute etc. magic here ??
subset(x, subset)
}
foo_1(ansombe, x1 > 5)
我希望得到与 subset(ansombe, x1 > 5)
相同的结果.此外,当参数传递到更深层次时,我希望同样的工作,即
I want this to get the same results as for subset(ansombe, x1 > 5)
. Also, I want the same to work when the argument is passed on to a deeper level, i.e.
foo_2 <- function(x, mysubset)
{
# some deparse, substitute etc. magic here ??
foo_1(x, mysubset)
}
foo_2(ansombe, x1 > 5)
这里我也想要和上面一样的结果.
Here also I want the same result as above.
到目前为止我尝试过的
我尝试了substitute
-deparse
、eval
-parse
的组合,比如
I tried a substitute
-deparse
, eval
-parse
combination, like
foo_1 <- function(x, mysubset)
{
tx <- deparse(substitute(mysubset))
subset(x, eval(parse(text=tx)))
}
foo_1(anscombe, x1 >5)
这很好,但我现在如何处理 foo_2
?
This is fine, but how do I go on for foo_2
now?
此外,我还记得 Thomas Lumley 的格言:
Also, I remember the dictum by Thomas Lumley:
如果答案是 parse() 你通常应该重新思考这个问题.-- Thomas Lumley(R-help,2005 年 2 月)
If the answer is parse() you should usually rethink the question. -- Thomas Lumley (R-help, February 2005)
所以,我想知道是否有比 eval
-parse
组合更好的方法.?有什么想法吗?
So, I was wondering if there is a better approach than an eval
-parse
combination.?
Any ideas?
附注.这个问题类似,但不包括更深的嵌套:传递子集参数一个子集函数
PS. This question is similar but does not include the deeper nesting: Pass subset argument through a function to subset
PPS:也许应用 plyr
中的 .
函数很有成效,但我不知道如何...
PPS: Maybe it is fruitful applying the .
function from plyr
, but I don't know how...
推荐答案
只要你尽可能拖延评估,这样的事情应该可以
As long as you delay the evaulation as long as possible, something like this should work
foo_1 <- function(x, mysubset)
{
do.call("subset", list(quote(x), substitute(mysubset)))
}
foo_2 <- function(x, mysubset)
{
do.call("foo_1", list(quote(x), substitute(mysubset)))
}
data(anscombe)
foo_1(anscombe, x1 > 5)
foo_2(anscombe, x1 > 5)
但是如果你打算用 mysubset
搞砸,你需要更加小心.这将有助于确切地知道你为什么这样做.
but if you plan on mucking about with mysubset
you would need to be more careful.It would help to know exactly why you are doing this.
这篇关于将非标准评估参数传递给子集函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!