如何在R中的数据框中按日期每8天获取值的总和 [英] How to get sum of values every 8 days by date in data frame in R

查看:120
本文介绍了如何在R中的数据框中按日期每8天获取值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不必经常使用R中的日期,但是我想这很容易。我有以下几年的每日数据,其中包含一些值,我希望每8天获得一次相关值的总和。最佳方法是什么?

I don't often have to work with dates in R, but I imagine this is fairly easy. I have daily data as below for several years with some values and I want to get for each 8 days period the sum of related values.What is the best approach?

任何

 str(temp)
'data.frame':648 obs. of  2 variables:
 $ Date : Factor w/ 648 levels "2001-03-24","2001-03-25",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ conv2: num  -3.93 -6.44 -5.48 -6.09 -7.46 ...

head(temp)
Date              amount
24/03/2001  -3.927020472
25/03/2001  -6.4427004
26/03/2001  -5.477592528
27/03/2001  -6.09462162
28/03/2001  -7.45666902
29/03/2001  -6.731540928
30/03/2001  -6.855206184
31/03/2001  -6.807210228
1/04/2001   -5.40278802

我尝试使用聚合函数,但由于某些原因,该函数不起作用,并且以错误的方式聚合:

I tried to use aggregate function but for some reasons it doesn't work and it aggregates in wrong way:

z <- aggregate(amount ~ Date, timeSequence(from =as.Date("2001-03-24"),to =as.Date("2001-03-29"), by="day"),data=temp,FUN=sum)


推荐答案

我更喜欢使用包 xts 进行此类操作。

I prefer the package xts for such manipulations.


  1. 我以动物园对象的身份读取了您的数据。

  1. I read your data, as zoo objects. see the flexibility of format option.

library(xts)
ts.dat <- read.zoo(text ='Date              amount
24/03/2001  -3.927020472
25/03/2001  -6.4427004
26/03/2001  -5.477592528
27/03/2001  -6.09462162
28/03/2001  -7.45666902
29/03/2001  -6.731540928
30/03/2001  -6.855206184
31/03/2001  -6.807210228
1/04/2001   -5.40278802',header=TRUE,format = '%d/%m/%Y')


  • 然后我提取给定期间的索引

  • Then I extract the index of given period

    ep <- endpoints(ts.dat,'days',k=8)
    


  • 最后,我将函数应用于每个索引的时间序列。 / p>

  • finally I apply my function to the time series at each index.

    period.apply(x=ts.dat,ep,FUN=sum )
    2001-03-29 2001-04-01 
    -36.13014  -19.06520 
    


  • 这篇关于如何在R中的数据框中按日期每8天获取值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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