【问题标题】:Programming with dplyr 0.3使用 dplyr 0.3 编程
【发布时间】:2014-11-12 20:16:01
【问题描述】:

我正在尝试使用新的下划线函数对标准评估provided in dplyr 0.3 进行分组和总结。但是,我在尝试使用 lapply 而不是循环时遇到了问题:

小例子

fruits <- c("APPLE", "PEAR", "BANANA")
makes <- c("HONDA", "FERRARI", "TESLA")
df <- data.frame(fruit = sample(fruits, 100, replace = T), 
                 make  = sample(makes, 100, replace = T), 
                 value = 1:100)
cols <- c("fruit", "make")

showTopTenFactors <- function(x, ...) x %>% 
                                      group_by_(...) %>% 
                                      summarise(cnt = n()) %>% 
                                      arrange(desc(cnt)) %>% 
                                      head(10)

现在这个循环给了我想要的输出

for(i in cols){
  showTopTenFactors(df, i) %>% print
}

Source: local data frame [3 x 2]

   fruit cnt
1  APPLE  49
2 BANANA  30
3   PEAR  21
Source: local data frame [3 x 2]

     make cnt
1   HONDA  35
2   TESLA  34
3 FERRARI  31

但是当我尝试用

替换它时
lapply(cols, showTopTenFactors, df)

我收到以下错误消息:

 Error in UseMethod("group_by_") : 
  no applicable method for 'group_by_' applied to an object of class "character"

【问题讨论】:

    标签: r functional-programming dplyr


    【解决方案1】:

    我认为您实际上不需要创建匿名函数。 lapply 应该能够传递一个参数,只要它被正确命名:

    > lapply(cols, showTopTenFactors, x=df)
    [[1]]
    Source: local data frame [3 x 2]
    
       fruit cnt
    1 BANANA  41
    2  APPLE  32
    3   PEAR  27
    
    [[2]]
    Source: local data frame [3 x 2]
    
         make cnt
    1 FERRARI  45
    2   TESLA  30
    3   HONDA  25
    

    您让“cols”值与函数中的 x 匹配。这不是特定于基于 dplyr 的函数,而是一个通用的 R 问题。

    【讨论】:

      【解决方案2】:

      将您的 lapply 语句更改为以下内容应该可以解决它:

      lapply(cols, FUN= function(x) showTopTenFactors(df, x))
      [[1]]
      Source: local data frame [3 x 2]
      
         fruit cnt
      1 BANANA  36
      2   PEAR  36
      3  APPLE  28
      
      [[2]]
      Source: local data frame [3 x 2]
      
           make cnt
      1   HONDA  39
      2   TESLA  33
      3 FERRARI  28
      

      在自定义函数中具体指定参数通常是apply 语句中的好方法。

      【讨论】:

        猜你喜欢
        • 2014-11-22
        • 2017-12-26
        • 2018-11-17
        • 2017-12-23
        • 1970-01-01
        • 1970-01-01
        • 2014-02-23
        • 2023-03-08
        • 1970-01-01
        相关资源
        最近更新 更多