【问题标题】:Non-standard evaluation of dot parameters网点参数的非标准评估
【发布时间】:2017-03-09 17:18:32
【问题描述】:

我有一个函数,我想包装另一个函数,将参数作为... 参数传递。我在学习如何使用 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 = ...)
  )
}

在此我的pythag_wrapper 将做一些额外的数据处理。和pythag 在我的情况下有两个以上的论点。该功能运行良好,符合预期。

test_data <- dplyr::data_frame(a = runif(10), b = runif(10), c = runif(10)) 

test_data %>%
  dplyr::mutate(
    root = pythag(a = b, b = c)
  )
## # A tibble: 10 × 4
##             a          b         c      root
##         <dbl>      <dbl>     <dbl>     <dbl>
## 1  0.19805337 0.05567241 0.9956758 0.9972311
## 2  0.22642799 0.18871552 0.8690659 0.8893195
## 3  0.09352032 0.57328658 0.7475573 0.9420719
## 4  0.40589832 0.71270806 0.8014196 1.0724860
## 5  0.35896302 0.85889027 0.8197176 1.1872782
## 6  0.66409819 0.02206298 0.1304790 0.1323312
## 7  0.45102742 0.76048535 0.5501899 0.9386410
## 8  0.48249177 0.93670363 0.8280114 1.2502066
## 9  0.05545819 0.12281684 0.9219704 0.9301148
## 10 0.47588862 0.40196106 0.0192433 0.4024214

我尝试了lazyeval::interplazy_eval::lazy_dots 等的各种组合,但我无法理解到底应该发生什么,更不用说如何解决我的问题了。

pythag_wrapper(test_data, a = "a", b = "b")

## Error: object 'x' not found 

【问题讨论】:

    标签: r dplyr lazy-evaluation nse


    【解决方案1】:

    代码中的问题在于如何处理点参数...

    稍微更改您的代码并“手动”重写包装器内的公式即可正常工作:

    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'))
    }
    

    【讨论】:

    • 这让我更进一步(并解决了 MWE),但我的真实案例返回 Error in UseMethod("as.lazy_dots") : no applicable method for 'as.lazy_dots' applied to an object of class "function",这仍然很迟钝。
    • 你能解释一下为什么你试图重写函数调用吗?这是解决此类问题的最干净的方法吗?
    猜你喜欢
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2015-02-17
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多