R脚本每<x>天平均值</x>

时间:2011-02-24 14:25:09

标签: r

我在查找如何计算“x”天的平均值时遇到了问题。如果我试图在1年内绘制这个csv文件,那么在绘图线上显示的数据太多了(截图附件)。我希望每隔几天(可能是2周,一周等)平均数据,所以线图不是那么难读。关于如何用R解决这个问题的任何建议?

results.csv

POSTS,PROVIDER,TYPE,DATE
29337,FTP,BLOG,2010-01-01
26725,FTP,BLOG,2010-01-02
27480,FTP,BLOG,2010-01-03
31187,FTP,BLOG,2010-01-04
31488,FTP,BLOG,2010-01-05
32461,FTP,BLOG,2010-01-06
33675,FTP,BLOG,2010-01-07
38897,FTP,BLOG,2010-01-08
37122,FTP,BLOG,2010-01-09
41365,FTP,BLOG,2010-01-10
51760,FTP,BLOG,2010-01-11
50859,FTP,BLOG,2010-01-12
53765,FTP,BLOG,2010-01-13
56836,FTP,BLOG,2010-01-14
59698,FTP,BLOG,2010-01-15
52095,FTP,BLOG,2010-01-16
57154,FTP,BLOG,2010-01-17
80755,FTP,BLOG,2010-01-18
227464,FTP,BLOG,2010-01-19
394510,FTP,BLOG,2010-01-20
371303,FTP,BLOG,2010-01-21
370450,FTP,BLOG,2010-01-22
268703,FTP,BLOG,2010-01-23
267252,FTP,BLOG,2010-01-24
375712,FTP,BLOG,2010-01-25
381041,FTP,BLOG,2010-01-26
380948,FTP,BLOG,2010-01-27
373140,FTP,BLOG,2010-01-28
361874,FTP,BLOG,2010-01-29
265178,FTP,BLOG,2010-01-30
269929,FTP,BLOG,2010-01-31

R剧本

library(ggplot2);
data <- read.csv("results.csv", header=T);
dts <- as.POSIXct(data$DATE, format="%Y-%m-%d");
attach(data);
a <- ggplot(dataframe, aes(dts,POSTS/1000, fill = TYPE)) + opts(title = "Report") + labs(x = NULL, y = "Posts (k)", fill = NULL);
b <- a + geom_bar(stat = "identity", position = "stack");
plot_theme <- theme_update(axis.text.x = theme_text(angle=90, hjust=1), panel.grid.major = theme_line(colour = "grey90"), panel.grid.minor = theme_blank(), panel.background = theme_blank(), axis.ticks = theme_blank(), legend.position = "none");
c <- b + facet_grid(TYPE ~ ., scale = "free_y");
d <- c + scale_x_datetime(major = "1 months", format = "%Y %b");
ggsave(filename="/root/results.png",height=14,width=14,dpi=600);

图形图像

enter image description here

2 个答案:

答案 0 :(得分:4)

试试这个:

Average <- function(Data,n){
    # Make an index to be used for aggregating
    ID <- as.numeric(as.factor(Data$DATE))-1
    ID <- ID %/% n
    # aggregate over ID and TYPE for all numeric data.
    out <- aggregate(Data[sapply(Data,is.numeric)],
      by=list(ID,Data$TYPE),
      FUN=mean)
    # format output
    names(out)[1:2] <-c("dts","TYPE")
    # add the correct dates as the beginning of every period
    out$dts <- as.POSIXct(Data$DATE[(out$dts*n)+1])
    out
}

dataframe <- Average(Data,3)

这适用于你给出的情节剧本。

一些评论:

  • 永远不会在函数名称(data,c,...)之后调用某个变量
  • 避免使用attach()。如果你这样做,之后添加detach(),否则你会在某些时候遇到麻烦。更好的方法是使用函数with()within()

答案 1 :(得分:3)

TTR包还有几个移动平均函数,只需一个语句即可完成:

library(TTR)
mavg.3day <- SMA(data$POSTS, n=3)  # Simple moving average

将“n”的不同值替换为所需的移动平均长度。