gpt4 book ai didi

r - dplyr 0.3.0.9000 如何正确使用 do()

转载 作者:行者123 更新时间:2023-12-04 10:47:45 24 4
gpt4 key购买 nike

试图在 SO 问题上重现结果:
dplyr: How to apply do() on result of group_by?

这是数据

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

我试图复制的结果是:
[[1]]
[,1] [,2] [,3]
[1,] "apple" "apple" "banana"
[2,] "banana" "cucumber" "cucumber"

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

产生上述结果的原始代码如下,不再有效:
> eaten %>% group_by(person) %>% do(function(x) combn(x$foods, m = 2))
Error: Results are not data frames at positions: 1, 2

尝试了几种使用 do() 函数的方法都无济于事。
> 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

似乎只有下面的一个适用于警告消息:
> 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

相信新版本下 do() 的行为必须有所改变。有哪些变化?使用 do() 的正确习惯用法/方法是什么?谢谢。

编辑:安装最新的 dplyr 并运行@hadley 建议的代码
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]>

EDIT2:需要按照@hadley 的建议提取列“x”
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"

最佳答案

在 Q 中移动 EDIT2 以回答以关闭问题:

最新 dplyr 0.3.0.2+,需要按照@hadley 的建议提取列“x”

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

关于r - dplyr 0.3.0.9000 如何正确使用 do(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26336180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com