我正在尝试将函数传递给另一个函数进行求值。我希望保留函数的名称,因为我将在命名输出时使用它。在下面的MWE中,我只打印名称。如果我将函数作为alist传入,而不是作为list传入,就可以做到这一点。
df <- data.frame(x=1:3)
foo <- function(df, a, i) {
# Insert a check along the lines of is.alist(a) here
print(paste('Applying', a[[i]], 'to the dataframe df'))
result <- eval(a[[i]])(df)
return(result)
}
a <- alist(min, sum)
foo(df, a, 2)
l <- list(min,sum)
foo(df, l, 2)这将给出以下输出
> a <- alist(min, sum)
> foo(df, a, 2)
[1] "Applying sum to the dataframe df"
[1] 6
>
> l <- list(min,sum)
> foo(df, l, 2)
Error in paste("Apply", a[[i]], "to the dataframe df") :
cannot coerce type 'builtin' to vector of type 'character' 我想检查foo内部并报告给用户,他们应该在alist中传递then函数。
有什么想法吗?
发布于 2020-07-07 22:00:20
alist不求值,list求值。它们是不一样的。如果你想使用list,你必须引用:
l <- list(quote(min) ,quote(sum))
foo(df, l, 2)
[1] "Applying sum to the dataframe df"
[1] 6发布于 2020-07-07 23:32:19
alist返回一个列表:
identical(alist(min, sum),
list(quote(min), quote(sum)))
#[1] TRUE 您不能测试列表是如何创建的。您可以测试列表元素的类型:
vapply(a, typeof, FUN.VALUE = "")
#[1] "symbol" "symbol"
vapply(l, typeof, FUN.VALUE = "")
#[1] "builtin" "builtin"但是让我推荐你重新设计你的函数。我不认为要求用户使用alist是一种好的做法。
https://stackoverflow.com/questions/62776687
复制相似问题