Tried to reproduce the result on a SO question: dplyr: How to apply do() on result of group_by?
Here is the data
person = c('Grace', 'Grace', 'Grace', 'Rob', 'Rob', 'Rob')
foods = c('apple', 'banana', 'cucumber', 'spaghetti', 'cucumber', 'banana')
eaten <- data.frame(person, foods, stringsAsFactors = FALSE)
Result that I was trying to replicate is:
[[1]]
[,1] [,2] [,3]
[1,] "apple" "apple" "banana"
[2,] "banana" "cucumber" "cucumber"
[[2]]
[,1] [,2] [,3]
[1,] "spaghetti" "spaghetti" "cucumber"
[2,] "cucumber" "banana" "banana"
The original code producing the result above is as below which no longer works:
> eaten %>% group_by(person) %>% do(function(x) combn(x$foods, m = 2))
Error: Results are not data frames at positions: 1, 2
Tried several ways to use do() function to no avail.
> eaten %>% group_by(person) %>% do(combn(.$foods, m = 2))
Error: Results are not data frames at positions: 1, 2
> eaten %>% group_by(person) %>% do(.$foods, combn, m =2)
Error: Arguments to do() must either be all named or all unnamed
> eaten %>% group_by(person) %>% do((combn(.$foods, m=2)))
Error: Results are not data frames at positions: 1, 2
Seems only the one below works with warning message though:
> eaten %>% group_by(person) %>% do(as.data.frame(combn(.$foods, m = 2)))
# person V1 V2 V3
# 1 Grace apple apple banana
# 2 Grace banana cucumber cucumber
# 3 Rob spaghetti spaghetti cucumber
# 4 Rob cucumber banana banana
# Warning messages:
# 1: In rbind_all(out[[1]]) : Unequal factor levels: coercing to character
# 2: In rbind_all(out[[1]]) : Unequal factor levels: coercing to character
Believe there must a change on the behavior of do() under new version. What are the changes? What is the right idiom / way to use do()? Thanks.
packageVersion("dplyr")
[1] ‘0.3.0.2’
eaten %>% group_by(person) %>% do(x = combn(.$foods, m = 2))
# Source: local data frame [2 x 2]
# Groups: <by row>
#
# person x
# 1 Grace <chr[2,3]>
# 2 Rob <chr[2,3]>
eaten2 <- eaten %>% group_by(person) %>% do(x = combn(.$foods, m = 2))
eaten2[["x"]]
# [[1]]
# [,1] [,2] [,3]
# [1,] "apple" "apple" "banana"
# [2,] "banana" "cucumber" "cucumber"
#
# [[2]]
# [,1] [,2] [,3]
# [1,] "spaghetti" "spaghetti" "cucumber"
# [2,] "cucumber" "banana" "banana"
Move EDIT2 in Q to answer to close the question:
For latest dplyr
0.3.0.2+, need to extract column "x" as suggested by @hadley
eaten2 <- eaten %>% group_by(person) %>% do(x = combn(.$foods, m = 2))
eaten2[["x"]]
# [[1]]
# [,1] [,2] [,3]
# [1,] "apple" "apple" "banana"
# [2,] "banana" "cucumber" "cucumber"
#
# [[2]]
# [,1] [,2] [,3]
# [1,] "spaghetti" "spaghetti" "cucumber"
# [2,] "cucumber" "banana" "banana
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With