【问题标题】:How to conver daily data over the period of 30 years to Monthly data for a multivariate series?如何将 30 年期间的每日数据转换为多元系列的每月数据?
【发布时间】:2018-11-21 10:19:03
【问题描述】:

我的数据框如下图:

 str(Rainfall_Complete)
'data.frame':   8221 obs. of  18 variables:
 $ Date          : Date, format: "1985-04-29" "1985-04-30" "1985-05-01" ...
 $ Month         : Ord.factor w/ 12 levels "Jan"<"Feb"<"Mar"<..:
 $ Season        : Factor w/ 4 levels "Monsoon","PostMonsoon",..:.
 $ Year          : chr  "1985" "1985" "1985" "1985" ...
 $ Stn A         : num  0 8.8 0 15 26.2 0 2.5 0 0 0 ...
 $ Stn B         : num  0 0 26 11 13.8 20 0.26 0 0 0 ...
 $ Stn C         : num  0.1 0 0 0 13.5 27 16 5 0 0 …

我想将上述每日时间序列转换为每月时间序列 我希望我的数据看起来像这样

Year  Month StnA   StnB   StnC……..

1985   Jan   150    100   120

1985   Feb   120     98    58

….

2010   Jan   200    100    87

2010   Feb   140    145    120

我尝试了以下方法,但它仅适用于单变量系列

library(dplyr)
Monthly_rainfall <- Rainfall_Complete %>% group_by(Year,Month)%>% summarise()

任何帮助将不胜感激

【问题讨论】:

  • 您需要先将年月转换为正确的日期格式,稍后使用您的代码即可进行转换
  • 如果您想在多个列上使用summarise,请尝试summarise_at。根据您的分组,您将能够同时获得多个列的sum
  • 也许padr::thicken() 会有所帮助。
  • 请看一下如何制作reproducible example,以便更容易提供帮助

标签: r dplyr xts lubridate


【解决方案1】:

您的尝试使用dplyr,但问题标记为xtslubridate,因此这里是使用带有reprex 的这些包的解决方案。

library(lubridate)
library(xts)

## Create some basic data
ans6 <- xts(anscombe[, 1:6], order.by = as.Date("2018-01-28") + 1:nrow(anscombe))

## Summary by month
mon6 <- apply.monthly(ans6, FUN = mean)

## Re-format
df6 <- as.data.frame(mon6)
df6$year <- year(rownames(df6))
df6$month <- month(rownames(df6), label = TRUE)

df6
## x1       x2       x3    x4       y1       y2 year month
## 2018-01-31 10.33333 10.33333 10.33333 8.000 7.523333 8.673333 2018   Jan
## 2018-02-08  8.50000  8.50000  8.50000 9.375 7.492500 7.061250 2018   Feb

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 2017-11-02
    • 2018-08-19
    • 2016-10-27
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多