[R] mean of a value of the last 2 hours

arun smartpink111 at yahoo.com
Thu Oct 25 16:50:49 CEST 2012


Hi,
May be this helps:
 new1<-with(myframe2,aggregate(cbind(Hunger,myframestime),by=list(ID=ID), function(x) mean(tail(x,2))))[,1:2]
 merge(myframe2,new1,by="ID",all=TRUE)
#     ID Hunger.x        myframestime Hunger.y
#1  Bert        2 2012-09-24 09:00:00      1.5
#2  Bert        2 2012-09-24 10:00:00      1.5
#3  Bert        1 2012-09-24 11:00:00      1.5
#4 Ernie        1 2012-09-24 09:00:00      1.0
#5 Ernie        1 2012-09-24 10:00:00      1.0
#6 Ernie        1 2012-09-24 11:00:00      1.0
A.K.




----- Original Message -----
From: Tagmarie <Ramgad82 at gmx.net>
To: r-help at r-project.org
Cc: 
Sent: Thursday, October 25, 2012 10:35 AM
Subject: [R] mean of a value of the last 2 hours

Hello, 
I have a data frame somewhat like that: 

myframe <- data.frame (ID=c("Ernie", "Ernie", "Ernie", "Bert", "Bert",
"Bert"), Timestamp=c("24.09.2012 09:00", "24.09.2012 10:00", "24.09.2012
11:00"), Hunger=c(1,1,1,2,2,1) )
myframestime <- as.POSIXct (strptime(as.character(myframe$Timestamp),
"%d.%m.%Y %H:%M"), tz="GMT")
myframe2 <- cbind (myframe,myframestime)
myframe2$Timestamp <- NULL  
myframe2

I want to add an additional column at the right and get in each row a value
which shows the mean of "hunger" of the last two hours. 

Does anyone know how that works? That would be very helpful. 



--
View this message in context: http://r.789695.n4.nabble.com/mean-of-a-value-of-the-last-2-hours-tp4647415.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.





More information about the R-help mailing list