【发布时间】:2014-12-08 04:41:02
【问题描述】:
尝试通过索引选择grouped_df 类对象的列会给出“错误:索引超出范围”。例如
x <- mtcars %>% group_by(am, gear) %>% summarise_each(funs(sum), disp, hp, drat)
class(x)
# "grouped_df" "tbl_df" "tbl" "data.frame"
# For some reason the first column can be selected...
x[1]
# Source: local data frame [4 x 1]
# Groups: am
# am
# 0
# 0
# 1
# 1
# ...but any index > 1 fails
x[2]
# Error: index out of bounds
# Coercing to data frame does the trick...
as.data.frame(x)[2]
# gear
# 3
# 4
# 4
# 5
#... and so does ungrouping
all(ungroup(x)[2] == as.data.frame(x)[2]) # TRUE
这是使用 R 版本 3.1.1 和 dplyr 0.3.0.2。我不确定这是一个错误还是故意的.. 有什么好的理由让它这样工作吗?我宁愿不必记得每次使用dplyr 后都取消分组我的数据框...
更新 对此进行深入研究后,我的猜测是定义 [.grouped_df this way 的动机是为了在调用时保留组,例如x[1:3](有效)。但是,当索引不是分组变量的一部分时,会抛出上述错误。也许可以对其进行修改,以便在这种情况下调用[.tbl_df 并同时引发警告......
更新 2 [.grouped_df 已在 dplyr (0.3.0.9000) 的开发版本中进行了修改。它仍然会引发错误,但现在更清楚了,指定了哪些分组变量不包括在内。
x[2]
# Error in `[.grouped_df`(x, 2) :
# cannot group, grouping variables 'am' not included
为了让我的代码在这种情况下不会崩溃,我发现的最佳解决方案是在 dplyr 命令链的末尾包含 %>% ungroup。
【问题讨论】:
-
在带有 dplyr_0.2 的 Windows 上使用 R 版本 3.1.0 我可以毫无问题地访问所有列。
-
我在 Mac 上使用 R 3.1.1 和 dplyr 0.3.0.2 时也遇到了这个错误。
-
我在 Ubuntu 上使用 R 3.1.1 和 dplyr 0.3.0.2 时遇到了同样的错误,但我认为我在使用 dplyr 0.2 时没有遇到这个问题。使用
dplyr的select()进行子集化可用于非分组变量,但我不能使用括号或基本subset()函数进行子集化。基于this issue,我猜这是故意的,但哇它让我难过一阵子。 -
(我实际上尝试恢复到 dplyr 0.2 并且这种行为在我的机器上保持不变。)