[英]dplyr: How to apply do() on result of group_by?
I'd like to use dplyr to group a table by one column, then apply a function to the set of values in the second column of each group. 我想使用dplyr将表分组为一列,然后将函数应用于每组第二列中的值集。
For instance, in the code example below, I'd like to return all of the 2-item combinations of foods eaten by each person. 例如,在下面的代码示例中,我想返回每个人吃的所有2项食物组合。 I cannot figure out how to properly supply the function with the proper column (foods) in the do()
function. 我无法弄清楚如何在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 ) )
Note that the example code in ?do
fails on my machine 请注意, ?do
中的示例代码在我的机器上失败
mods <- do(carriers, failwith(NULL, lm), formula = ArrDelay ~ date)
Let us define eaten
like this: 让我们定义eaten
这样的:
eaten <- data.frame(person, foods, stringsAsFactors = FALSE)
1) Then try this: 1)然后试试这个:
eaten %.% group_by(person) %.% do(function(x) combn(x$foods, m = 2))
giving: 赠送:
[[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) To be able to do something near to what @Hadley describes in the comments without waiting for a future version of dplyr try this where do2
is found here : 2)为了能够做到接近的东西是什么@Hadley介绍了评论,而无需等待dplyr的未来版本试试这个地方do2
发现这里 :
library(gsubfn)
eaten %.% group_by(person) %.% fn$do2(~ combn(.$foods, m = 2))
giving: 赠送:
$Grace
[,1] [,2] [,3]
[1,] "apple" "apple" "banana"
[2,] "banana" "cucumber" "cucumber"
$Rob
[,1] [,2] [,3]
[1,] "spaghetti" "spaghetti" "cucumber"
[2,] "cucumber" "banana" "banana"
Note: The last line of the question giving the code in the help file also fails for me. 注意:在帮助文件中提供代码的问题的最后一行也对我失败了。 This variation of it works for me: do(jan, lm, formula = ArrDelay ~ date)
. 这种变化适用于我: do(jan, lm, formula = ArrDelay ~ date)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.