R 网点参数的非标准评价
我有一个函数,我想包装另一个函数,将参数作为R 网点参数的非标准评价,r,dplyr,lazy-evaluation,nse,R,Dplyr,Lazy Evaluation,Nse,我有一个函数,我想包装另一个函数,将参数作为…参数传递。我在学习如何使用lazyeval构造底层函数调用时遇到了困难,这里有一个不错的MWE library(dplyr) pythag <- function(a, b){ sqrt(a^2 + b^2) } pythag_wrapper <- function(data, ...){ dplyr::mutate_(data, root = lazyeval::interp(~pythag(x), x = ...)
…
参数传递。我在学习如何使用lazyeval
构造底层函数调用时遇到了困难,这里有一个不错的MWE
library(dplyr)
pythag <- function(a, b){
sqrt(a^2 + b^2)
}
pythag_wrapper <- function(data, ...){
dplyr::mutate_(data,
root = lazyeval::interp(~pythag(x), x = ...)
)
}
我尝试了各种各样的组合,包括lazyeval::interp
,lazy\u eval::lazy\u dots
,但我不知道到底应该发生什么,更不用说如何解决我的问题了
pythag_wrapper(test_data, a = "a", b = "b")
## Error: object 'x' not found
代码中的问题在于如何处理dots参数
…
稍微更改代码并在包装器中“手动”重写公式,效果良好:
pythag_wrapper <- function(data, ...){
# From ... argument get names and values
dots = list(...)
# 'Write' the formula: ' ~ pythag(a = val1, b = val2)'
yourformula = as.formula(
paste0(" ~ pythag(",
paste0(names(dots), " = ", unlist(dots), collapse = ", "),
")")
)
# Apply the mutate_. The setNames here is what you need to
# apply the right name to the resulting column
dplyr::mutate_(data, .dots = setNames(list(yourformula), 'root'))
}
pythag\u wrapper这让我走得更远了一点(并解决了MWE),但我的真实案例返回了UseMethod中的错误(“as.lazy\u dots”):没有适用于“as.lazy\u dots”的方法应用于类“function”
的对象,该类对象仍然非常迟钝。您能解释一下为什么试图重写函数调用吗?这是解决这类问题最干净的方法吗?
pythag_wrapper <- function(data, ...){
# From ... argument get names and values
dots = list(...)
# 'Write' the formula: ' ~ pythag(a = val1, b = val2)'
yourformula = as.formula(
paste0(" ~ pythag(",
paste0(names(dots), " = ", unlist(dots), collapse = ", "),
")")
)
# Apply the mutate_. The setNames here is what you need to
# apply the right name to the resulting column
dplyr::mutate_(data, .dots = setNames(list(yourformula), 'root'))
}