【问题标题】:Lazy evaluation when writing functions with dplyr使用 dplyr 编写函数时的延迟评估
【发布时间】:2017-03-03 15:24:37
【问题描述】:

我想使用 dplyr 函数编写一个函数来输出 z 中每个元素有多少个唯一元组 (z, y)。函数看起来像这样

library(tidyverse)

data <- data_frame(z = rep(c('a', 'b'), 50), 
       y = sample(letters[13:18], size = 100, T))

foo1 <- function(data, x, n){

  library(lazyeval)
  data %>%
    group_by_(lazy(n, x)) %>%
    filter(row_number() == 1) %>%
    ungroup() %>% 
    group_by_(lazy(x)) %>%
    summarise(nr_x = n()) %>%
    arrange(desc(nr_x))

}

foo1(data, x = z, n = y)

但我收到以下错误:

Error in as.lazy_dots(list(...)) : object 'z' not found 

这个更简单的函数,看起来与前面的非常相似,但运行良好。

foo <- function(data, x, n){

  library(lazyeval)
  data %>%
    group_by_(lazy(n, x)) %>%
    summarise(n = n())
}

有什么办法解决这个问题吗?

【问题讨论】:

  • 你到底想要什么,需要的函数的参数是什么,想要的输出是什么?例如,unique(data) %&gt;% count(z) 是否适合您?此外,将library 调用放入函数定义中是一件坏事。

标签: r dplyr lazy-evaluation


【解决方案1】:

8 个月后回到这个问题,我没有收到以前在运行 foo1 时遇到的错误。不知道为什么。

但我决定使用更新的 tidyeval 方法来解决这个问题。以下对我来说很好:

library(tidyverse)

data <- data_frame(z = rep(c('a', 'b'), 50), 
   y = sample(letters[13:18], size = 100, T))

foo_tidyeval <- function(data, x, n){
  x <- enquo(x)
  n <- enquo(n)

  data %>%
    group_by(!!n, !!x) %>%
    filter(row_number() == 1) %>%
    ungroup() %>% 
    group_by_(x) %>%
    summarise(nr_x = n()) %>%
    arrange(desc(nr_x))
}

foo_tidyeval(data, x = z, n = y)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-01
    • 2016-08-14
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多