将每日数据统计到月/年 [英] Aggregate Daily Data to Month/Year intervals
问题描述
我想要一个第二个数据框,所以我可以喂它到一个情节。
任何您可以提供的帮助将不胜感激!
编辑:作为参考:
> str(temp)
'data.frame':215746 obs。的2个变量:
$ date:POSIXct,格式:2011-02-012011-02-012011-02-01...
$金额:num 1.67 83.55 24.4 21.99 98.88 ...
>头(临时)
日期金额
1 2011-02-01 1.670
2 2011-02-01 83.550
3 2011-02-01 24.400
4 2011- 02-01 21.990
5 2011-02-03 98.882
6 2011-02-03 24.900
可能是一个更优雅的解决方案,但分为几个月和几年,其中 strftime()
然后 aggregate()
ing应该这样做。然后重新组合绘图日期。
x< - as.POSIXct(c(2011-02-01, 2011-02-01,2011-02-01))
mo< - strftime(x,%m)
yr< - strftime(x,%Y)
amt< - runif(3)
dd< - data.frame(mo,yr,amt)
dd.agg< - 聚合(amt〜mo + yr,dd,FUN = sum)
dd.agg $ date< - as.POSIXct(paste(dd.agg $ yr,dd.agg $ mo,01,sep = - ))
I don't often have to work with dates in R, but I imagine this is fairly easy. I have a column that represents a date in a dataframe. I simply want to create a new dataframe that summarizes a 2nd column by Month/Year using the date. What is the best approach?
I want a second dataframe so I can feed it to a plot.
Any help you can provide will be greatly appreciated!
EDIT: For reference:
> str(temp)
'data.frame': 215746 obs. of 2 variables:
$ date : POSIXct, format: "2011-02-01" "2011-02-01" "2011-02-01" ...
$ amount: num 1.67 83.55 24.4 21.99 98.88 ...
> head(temp)
date amount
1 2011-02-01 1.670
2 2011-02-01 83.550
3 2011-02-01 24.400
4 2011-02-01 21.990
5 2011-02-03 98.882
6 2011-02-03 24.900
There is probably a more elegant solution, but splitting into months and years with strftime()
and then aggregate()
ing should do it. Then reassemble the date for plotting.
x <- as.POSIXct(c("2011-02-01", "2011-02-01", "2011-02-01"))
mo <- strftime(x, "%m")
yr <- strftime(x, "%Y")
amt <- runif(3)
dd <- data.frame(mo, yr, amt)
dd.agg <- aggregate(amt ~ mo + yr, dd, FUN = sum)
dd.agg$date <- as.POSIXct(paste(dd.agg$yr, dd.agg$mo, "01", sep = "-"))
这篇关于将每日数据统计到月/年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!