【问题标题】:dplyr: How to apply do() on result of group_by?dplyr:如何在 group_by 的结果上应用 do()?
【发布时间】:2014-03-04 20:34:41
【问题描述】:

我想使用 dplyr 按一列对表进行分组,然后将函数应用于每组第二列中的一组值。

例如,在下面的代码示例中,我想返回每个人所吃食物的所有 2 项组合。我无法弄清楚如何在do() 函数中正确地为函数提供正确的列(食物)。

library(dplyr)

person = c( 'Grace', 'Grace', 'Grace', 'Rob', 'Rob', 'Rob' )
foods   = c( 'apple', 'banana', 'cucumber', 'spaghetti', 'cucumber', 'banana' )
eaten  = data.frame(person, foods)

by_person = group_by(eaten, person)

# How to do this?
do( by_person, combn( x = foods, m = 2 ) )

请注意,?do 中的示例代码在我的机器上失败了

mods <- do(carriers, failwith(NULL, lm), formula = ArrDelay ~ date)

【问题讨论】:

标签: r dplyr


【解决方案1】:

让我们这样定义eaten

eaten <- data.frame(person, foods, stringsAsFactors = FALSE)

1)然后试试这个:

eaten %.% group_by(person) %.% do(function(x) combn(x$foods, m = 2))

给予:

[[1]]
     [,1]     [,2]       [,3]      
[1,] "apple"  "apple"    "banana"  
[2,] "banana" "cucumber" "cucumber"

[[2]]
     [,1]        [,2]        [,3]      
[1,] "spaghetti" "spaghetti" "cucumber"
[2,] "cucumber"  "banana"    "banana"  

2) 为了能够在不等待未来版本的 dplyr 的情况下做类似于 @Hadley 在 cmets 中描述的事情,请尝试在 do2 找到 here 的位置:

library(gsubfn)
eaten %.% group_by(person) %.% fn$do2(~ combn(.$foods, m = 2))

给予:

$Grace
     [,1]     [,2]       [,3]      
[1,] "apple"  "apple"    "banana"  
[2,] "banana" "cucumber" "cucumber"

$Rob
     [,1]        [,2]        [,3]      
[1,] "spaghetti" "spaghetti" "cucumber"
[2,] "cucumber"  "banana"    "banana"  

注意:在帮助文件中给出代码的问题的最后一行对我来说也失败了。它的这种变体对我有用:do(jan, lm, formula = ArrDelay ~ date)

【讨论】:

  • 在 dplyr 的未来版本中,您将能够执行更多类似 do(combn(.$foods, m = 2)) 的操作,并且组件将自动使用有用的名称。
  • 非常感谢您提供有用的解决方案!第一行 stringsAsFactors 中的小错误。
  • 这次介绍了一个新的:)
  • 我认为dplyr 自创建此答案(#1)以来已发生变化。其中一项更改是从%.% 变为%&gt;%。我摆弄了一下,下面的代码产生了一个基本上具有所需输出的 ​​tibble,我认为:eaten %&gt;% group_by(person) %&gt;% do(k=combn(.$foods, m = 2)) 这里,k 是 tibble 中的列,其中每个元素都是一个矩阵,其中每列有两种可能吃的独特食物类型由那个人,三个独特的对有三列。
  • 如上所述,这是在一个新问题中重新访问:stackoverflow.com/q/26336180/8400969
猜你喜欢
  • 2018-10-06
  • 2016-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
  • 2018-05-20
  • 2017-07-12
相关资源
最近更新 更多