R:每月汇总行 [英] R: Summarize rows per month

查看:83
本文介绍了R:每月汇总行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个数据框,其中包含一列带有日期的列和一列带有数值的列。我希望此数据框按月分组,并在每个对应月份对其他列中的所有数值求和。

I have made a dataframe which has a column with dates and columns with numeric values. I want this dataframe to group itself by month and summerize all the numeric values from the other columns per corresponding month.

这是我的数据框示例:

capture.date  Test1  Test2  Test3
2016-03-18      0      1      1
2016-03-18      1      1      1
2016-03-20      2      1      1
2016-04-12      1      0      1

我已经尝试了一些代码:

I already tried some code:

df %>% 
  group_by(capture.date) %>% 
  summarise_each(funs(sum))

和:

aggregate(df[2:4], by=df["capture.date"], sum)

,但是这两个选项都返回数据框,这些数据框按每日日期而不是月份进行汇总。我该如何按月而不是按日汇总?

but both of these options return dataframes which summarize by daily date instead of month. How can I make it summarize by month instead of by day?

所需的输出:

capture.date  Test1  Test2  Test3
2016-03         3      3      3     
2016-04         1      0      1


推荐答案

您可以将日期提取为<$ c $%Y-%m 格式,格式为 group_by()并使用 summarise_if() summarise_at()来选择

You can extract dates into the %Y-%m format in group_by() and use summarise_if() or summarise_at() to select which variables get be summed.

(确认 capture.date Date class)

(Confirm that capture.date is Date class)

df %>%
  group_by(Date = strftime(capture.date, "%Y-%m")) %>%
  summarise_if(is.numeric, sum)

# # A tibble: 2 x 4
#   Date    Test1 Test2 Test3
#   <chr>   <int> <int> <int>
# 1 2016-03     3     3     3
# 2 2016-04     1     0     1

这篇关于R:每月汇总行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆