2014-01-25 196 views
0

请帮我看这个.. 所以我每天都有32年的观察(数据框)。 (因此总共大约11659行:有一些缺失的行) 我想计算每个第365个时间间隔的每列平均值(即32年期间的每个Jan-01,32年期间的每个Jan-02等等)每第n行跳列平均值

所以输出总共有365行,每行是365行间隔的32行平均值 有没有什么建议?我找到了类似的情况,并尝试了他们的解决方案并修改了一下,但输出结果不正确,特别是我不明白下面sapply部分..

df <-data.frame(x=c(1:10000),y=c(1:10000)) 
byapply <- function(x, by, fun, ...) 
{ 
# Create index list 
if (length(by) == 1) 
{ 
    nr <- nrow(x) 
    split.index <- rep(1:ceiling(nr/by), each = by, length.out = nr) 
} else 
{ 
    nr <- length(by) 
    split.index <- by 
} 
index.list <- split(seq(from = 1, to = nr), split.index) 

# Pass index list to fun using sapply() and return object #this is where I am lost 
sapply(index.list, function(i) 
     { 
      do.call(fun, list(x[, i], ...)) 
     }) 
} 

感谢您的时间..

+0

INDEX.LIST <-split(SEQ(从= 1到= NR),split.index)该行似乎也并不正确,我... – kclick

+1

如果您使用天气观测,如何处理闰年?最好为您的数据生成一些新的列,实际上是日期,一年中的哪一天。然后你可以使用apply函数。 – Bangyou

+0

是的,这也是我得到的问题。我需要重新汇编我的数据,感谢您的意见。 – kclick

回答

0

虽然可能有一个特殊的功能,这不正是你所需要的,这里是用ave一个解决方案:

set.seed(1) 
dates = seq(from=as.Date("1970-01-01"), as.Date("2000-01-01"), by="day") 
df <- data.frame(val1=runif(length(dates)), 
       val2=rchisq(length(dates), 10)) 
day <- format(dates, "%j") # day of year (1:366) 

df <- cbind(df, setNames(as.data.frame(sapply(df, function(x) { 
    ave(x, day) # calculate mean by day for df$val1 and df$val2 
})), paste0(names(df), "_mean"))) 

head(df[1:365, 3:4], 3) 
# val1_mean val2_mean 
# 1 0.5317151 10.485001 
# 2 0.5555664 10.490968 
# 3 0.6428217 10.763027 

也就是说,如果我理解正确你的任务。

1

如何使用plyr包:

require(plyr) # for aggregating data 

require(plyr) # for aggregating data 

series<-data.frame(date=as.Date("1964-01-01")+(1:100000), 
        obs=runif(10000), 
        obs2=runif(10000), 
        obs3=runif(10000)) 

ddply(series,      # run on series df 
     .(DOY=format(date,"%j")), # group by string of day and month (call col DOY) 
     summarise,     # tell the function to summarise by group (day of year) 
     daymean=mean(obs),   # calculate the mean 
     daymean2=mean(obs2),  # calculate the mean 
     daymean3=mean(obs3)   # calculate the mean 
) 

# DOY daymean daymean2 daymean3 
#1 001 0.4957763 0.4882559 0.4944281 
#2 002 0.5184197 0.4970996 0.4720893 
#3 003 0.5192313 0.5185357 0.4878891 
#4 004 0.4787227 0.5150596 0.5317068 
#5 005 0.4972933 0.5065012 0.4956527 
#6 006 0.5112484 0.5276013 0.4785681 
#...