【问题标题】:Breaking NSE function in new dplyr version在新的 dplyr 版本中破坏 NSE 功能
【发布时间】:2017-06-22 00:30:29
【问题描述】:

当更新到最新版本的软件包 dplyr 时,我使用 NSE 的功能会中断。我想知道新版本如何改变它以及如何修复它。我尝试在每个变量名之前使用.data$.env$,但似乎无法正常工作。

这是我的自定义函数:

t_ppond <- function(w, v){
  arguments <- as.list(match.call())

  y <- eval(arguments$w)
  x <- eval(arguments$v)

    d <- data.frame("yy" = y, 
                    "xx" = x)
    tt <- sum(d$yy)

    dff <- d %>%
      mutate("sh" = yy/tt) %>% 
      mutate("rr" = xx*sh)

  sum(dff$rr)
}

这就是我使用它的目的(从变量计算加权平均值):

data(iris)
iris %>% 
  group_by(Species) %>% 
  summarise("new" = t_ppond(Sepal.Length, Petal.Width))

以上代码在更新前运行良好。现在我明白了:

Error in summarise_impl(.data, dots) : 
  Evaluation error: object 'Sepal.Length' not found.

【问题讨论】:

    标签: r dplyr summarize


    【解决方案1】:

    您确定需要对此进行非标准评估吗?你有一个自定义函数,只需要接受两个向量,所以你可以这样写:

    t_ppond <- function(w, v){
        d <- data.frame("yy" = w, 
                        "xx" = v)
        tt <- sum(d$yy)
    
        dff <- d %>%
            mutate("sh" = yy/tt) %>% 
            mutate("rr" = xx*sh)
    
        sum(dff$rr)
    }
    
    data(iris)
    iris %>% 
        group_by(Species) %>% 
        summarise("new" = t_ppond(Sepal.Length, Petal.Width))
    

    输出:

    # A tibble: 3 x 2
         Species       new
          <fctr>     <dbl>
    1     setosa 0.2480224
    2 versicolor 1.3352089
    3  virginica 2.0333030
    

    【讨论】:

    • 你说的太对了!我陷入了试图让它发挥作用的过程中!谢谢!
    猜你喜欢
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    相关资源
    最近更新 更多