【发布时间】:2019-11-12 19:02:48
【问题描述】:
library(dplyr)
library(zoo)
df_a <- iris %>%
group_by(Species) %>%
summarise(mean_petal_length = mean(Petal.Length))
sample_n(df_a, 2)
这会按预期返回 2 行随机汇总的 iris,尽管每个组只有一行 Species。
但是,下面的另一个示例的行为似乎有所不同。
df_b <- iris %>%
group_by(Species) %>%
mutate(Petal.Length = na.locf(Petal.Length))
# Now df_b is the same with iris in terms of data contents
# since there's no missing vales in Petal.Length
sample_n(df_b, 60)
我希望得到 60 个随机行的 df_b,但这给了我一条错误消息:size 必须小于或等于 50(数据大小),设置 replace = TRUE 以使用带放回抽样。
我可以看到这是因为每个组 Species 只有 50 行,在这种情况下,我必须在 mutate 之后 ungroup 才能获得预期的输出。我仍然不明白为什么会有这种差异。
【问题讨论】: