[R] loop with date

jim holtman jholtman at gmail.com
Tue Nov 27 16:18:50 CET 2012


Here is an example of an approach:

> myframe <- data.frame (Timestamp=c("24.09.2012 09:00", "24.09.2012 10:00",
+ "24.09.2012 11:00",
+                                    "25.09.2012 09:00", "25.09.2012 10:00",
+ "25.09.2012 11:00"),
+                         Speed=c(1,1,2,5,1,6))
> myframestime <- as.POSIXct (strptime(as.character(myframe$Timestamp),
+ "%d.%m.%Y %H:%M"), tz="GMT")
> myframe2 <- cbind (myframe,myframestime)
> myframe2$Timestamp <- NULL
> myframe2
  Speed        myframestime
1     1 2012-09-24 09:00:00
2     1 2012-09-24 10:00:00
3     2 2012-09-24 11:00:00
4     5 2012-09-25 09:00:00
5     1 2012-09-25 10:00:00
6     6 2012-09-25 11:00:00
>
> # split the dataframe into "days' and then find average of Speed (for example)
> tapply(myframe2$Speed, cut(myframe2$myframestime, 'day'), mean)
2012-09-24 2012-09-25
  1.333333   4.000000
>
>



On Tue, Nov 27, 2012 at 9:02 AM, Tagmarie <Ramgad82 at gmx.net> wrote:
> Hello,
> I tried to construct my very first loop today and completly failed :-(
> Maybe someone can help me?
> I have a dataframe somewhat like this one:
>
> myframe <- data.frame (Timestamp=c("24.09.2012 09:00", "24.09.2012 10:00",
> "24.09.2012 11:00",
>                                    "25.09.2012 09:00", "25.09.2012 10:00",
> "25.09.2012 11:00"),
>                         Speed=c(1,1,2,5,1,6))
> 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 construct a loop for every day, i.e. for each day I want to do
> some calculations.
> (I know in the example it would be easier to do it differently, my real data
> are little more complex).
>
> And BTW: Thanks for helping me earlier today with that other problem :-)
>
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/loop-with-date-tp4650961.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.



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.




More information about the R-help mailing list