6

我想要一个调用subset并传递subset参数的函数:

df <- data.frame(abc=c("A","A","B","B"),value=1:4)
subset(df,abc=="A")
## works of course:
#  abc value
#1   A     1
#2   A     2

mysubset <- function(df,ssubset)
  subset(df,ssubset)

mysubset(df,abc=="A")
## Throws an error
# Error in eval(expr, envir, enclos) : object 'abc' not found

mysubset2 <- function(df,ssubset)
  subset(df,eval(ssubset))

mysubset2(df,expression(abc=="A"))
## Works, but needs expression

我尝试了substitute,但找不到正确的组合。我怎样才能得到这个工作?

4

2 回答 2

13

你也需要eval()并且parse()在那里:

mysubset <- function(df, ssubset) {
  subset(df, eval(parse(text=ssubset)))
}
mysubset(df, "abc=='A'")
#   abc value
# 1   A     1
# 2   A     2

"请注意,您需要嵌套引号,因此根据需要在和之间来回切换'


根据您的评论,也许这样的事情也很有趣:

mysubset <- function(df, ...) {
  ssubset <- deparse(substitute(...))
  subset(df, eval(parse(text = ssubset)))
}

用法:mysubset(df, abc=='A')

于 2012-08-09T10:08:29.393 回答
5

A5C1D2H2I1M1N2O1R2T1 答案有效,但您可以通过简单地使用以下方法跳过整个解析/解析周期:

mysubset <- function(df, p) {
  ps <- substitute(p)
  subset(df, eval(ps))
}
于 2018-06-07T21:24:45.047 回答