R: How to compute mean of every 10 lines of a variable -
i have datasets collected every 1 min, have replace data mean of 10 mins data. have r code.
for(k in 1:(length(temp[,1])/10)){ temp2[k,1]<-temp[1,1] temp2[k,2]<-temp[k*10,2] temp2[k,3]<-mean(na.omit(as.numeric(temp[((k-1)*10+1):k*10,3]))) }
however, efficiency of code tooooo low. , 1 more question. because of missing data, time variable not continuous. , have compute data of every true 10 mins (that 2014-01-01 00:00 2014-01-01 00:10, example), no matter how many obs in 10 mins. loop goes to
tmp<-na.omit(temp[temp[,2]>(st+600*(k-1)) & temp[,2]<=(st+600*k),]) temp2[k,1]<-tmp[1,1] temp2[k,2]<-st+600*k temp2[k,3]<-mean(na.omit(as.numeric(tmp[,3])))
which cannot bearable. , cannot handle case "some months missing". so, how can solve in r, while efficiency not low.
original data:
time var1 2014-01-01 00:01 10 2014-01-01 00:02 12 2014-01-01 00:03 43 ... 2014-01-01 00:10 52
desired output:
time var1 2014-01-01 00:10 (mean of every 10 mins) 2014-01-01 00:20 (mean of every 10 mins) ...
look @ xts
package, , period.apply
function endpoints
assuming can data xts object (in case called xt.data
, following work.
# example data times <- seq(sys.time()-50000,sys.time(),by=60) mydt <- data.frame(time = times[sample(seq_along(times),size=300)], test = runif(300)) xt.data <- as.xts(mydt[,2], order.by= mydt[['time']]) period.apply(xt.data, endpoints(xt.data,'minutes',10),mean)
Comments
Post a Comment