[R] Divide a Time column each K seconds

arun smartpink111 at yahoo.com
Fri Oct 4 04:36:09 CEST 2013


Hi,
Try:
 set.seed(45)
 df1<- data.frame(datetime=as.POSIXct("2011-05-25",tz="GMT")+1:200,value=sample(1:40,200,replace=TRUE),value2= sample(45:90,200,replace=TRUE))

res<-  with(df1,aggregate(cbind(value,value2),list(as.POSIXct(cut(datetime,breaks="5 sec"))+4),mean))
colnames(res)[1]<- colnames(df1)[1]
 head(res)
#             datetime value value2
#1 2011-05-25 00:00:05  16.0   67.4
#2 2011-05-25 00:00:10  10.8   60.0
#3 2011-05-25 00:00:15  20.2   65.2
#4 2011-05-25 00:00:20  17.8   65.2
#5 2011-05-25 00:00:25  21.2   81.6
#6 2011-05-25 00:00:30  21.4   56.2


#or
library(plyr)
res2<- ddply(df1,.(datetime=as.POSIXct(cut(df1$datetime,breaks="5 sec"))+4
),numcolwise(mean))
 head(res2)
#             datetime value value2
#1 2011-05-25 00:00:05  16.0   67.4
#2 2011-05-25 00:00:10  10.8   60.0
#3 2011-05-25 00:00:15  20.2   65.2
#4 2011-05-25 00:00:20  17.8   65.2
#5 2011-05-25 00:00:25  21.2   81.6
#6 2011-05-25 00:00:30  21.4   56.2



#or
library(xts)
originalTZ <- Sys.getenv("TZ")
Sys.setenv(TZ = "GMT")

xt1<- xts(df1[,2:3],order.by=df1[,1])
indx<-endpoints(xt1,'secs',5)
 res3<-period.apply(xt1,c(0,indx[-c(1,length(indx))]+1),FUN=mean)
 head(res3)
#                    value value2
#2011-05-25 00:00:05  16.0   67.4
#2011-05-25 00:00:10  10.8   60.0
#2011-05-25 00:00:15  20.2   65.2
#2011-05-25 00:00:20  17.8   65.2
#2011-05-25 00:00:25  21.2   81.6
#2011-05-25 00:00:30  21.4   56.2

Sys.setenv(TZ = originalTZ)

A.K.


Hi, I am new to R and to this forum. 
I have to do a project for school and I have to calculate the mean 
of a set of values corresponding to certain times (in two columns). 
I will need to calculate the mean of the values every K seconds and I
 dont know how to divide my Time column or to link the values to their 
corresponding period. 
Could you give me a hand on this? 

Cheers!



More information about the R-help mailing list