如何按日汇总日期

时间:2017-08-30 13:36:56

标签: r date dataframe aggregate

我有以下数据框。我需要按日汇总日期,其他所有列都按当天汇总。

输入:

 Date               mean      MAT             RA
6/10/2017 0:00      58.2275  72.14193702      100.22691322
6/10/2017 0:15      58.2055  75.14193702      102.22691322
6/10/2017 0:30      58.249   76.14193702      105.22691322
6/11/2017 13:45     60.2275  80.14193702      110.22691322
6/11/2017 14:00     65.2055  82.14193702      120.22691322
6/11/2017 14:15     66.2275  81.14193702      115.22691322

预期输出:

   Date            mean     MAT     RA
  6/10/2017        58.2     74      102
  6/11/2017        63.33    81      115

1 个答案:

答案 0 :(得分:0)

我们可以使用dplyrlubridate中的功能。 dt2是最终输出。

library(dplyr)
library(lubridate)

dt2 <- dt %>%
  mutate(Date = mdy_hm(Date)) %>%
  mutate(Date = as.Date(Date)) %>%
  group_by(Date) %>%
  summarise_all(funs(mean(.)))

dt2
# A tibble: 2 x 4
        Date     mean      MAT       RA
      <date>    <dbl>    <dbl>    <dbl>
1 2017-06-10 58.22733 74.47527 102.5602
2 2017-06-11 63.88683 81.14194 115.2269

数据

dt <- read.table(text = "Date               mean      MAT             RA
'6/10/2017 0:00'      58.2275  72.14193702      100.22691322
'6/10/2017 0:15'      58.2055  75.14193702      102.22691322
'6/10/2017 0:30'      58.249   76.14193702      105.22691322
'6/11/2017 13:45'     60.2275  80.14193702      110.22691322
'6/11/2017 14:00'     65.2055  82.14193702      120.22691322
'6/11/2017 14:15'     66.2275  81.14193702      115.22691322",
                 header = TRUE, stringsAsFactors = FALSE)