【问题标题】:Why is the R aggregation dropping data rows?为什么 R 聚合会删除数据行?
【发布时间】:2020-05-14 23:01:29
【问题描述】:

我有一个包含 2 列的数据框:日期和观察结果。数据由每个日期的多个观察值组成。

 str(observations)
tibble [2,599 × 2] (S3: tbl_df/tbl/data.frame)
 $ date        : chr [1:2599] "1/22/20" "1/22/20" "1/22/20" "1/22/20" ...
 $ observation : num [1:2599] 0 0 0 0 0 0 0 0 0 0 ...

> tail(observations)
# A tibble: 6 x 2
  date    observation
  <chr>       <dbl>
1 5/13/20      4127
2 5/13/20      1042
3 5/13/20     14306
4 5/13/20      1066
5 5/13/20         0
6 5/13/20        89

我想对这些观察结果进行小计,以便为每个日期生成一行,所以我使用了这个函数:

subs <- aggregate(cbind(observation) ~ date,data=observations, FUN = sum, na.rm = TRUE)

但输出缺少原始最后 4 天的任何行:

> tail(subs)
      date observation
108 5/4/20    128269
109 5/5/20    130593
110 5/6/20    131890
111 5/7/20    133991
112 5/8/20    135840
113 5/9/20    137397

【问题讨论】:

  • 使用aggregate(cbind(observation) ~ date,data=observations, FUN = sum, na.rm = TRUE, na.action = NULL)
  • 尝试了akrun的建议,但没有任何乐趣。
  • 你可以试试library(dplyr); observations %&gt;% group_by(date) %&gt;% summarisee(Sum = sum(observation, na.rm = TRUE))
  • 你能创建一个可以重现此行为的小型可重现示例吗?

标签: r dataframe tidyr


【解决方案1】:

我很抱歉。在进一步调查中,聚合函数似乎无序地返回了该数据。我重新排序了数据框并确认所有日期都已计算在内。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 2012-08-31
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 2012-05-14
    相关资源
    最近更新 更多