FriendOfDolphins
FriendOfDolphins

Reputation: 11

R Programming: Create hourly time intervals in an array with for loop

I have a simple for loop that is not returning what I need:

    time_bin[1] <- conversion_frame$time[1]

    for (t in 1:23)
        time_bin[t+1] <- as.POSIXct(time_bin[t]) +3600

In console I get this returning

     time_bin[1]
     [1] "2015-07-23 00:00:01"

And the equation returns the time as well

as.POSIXct(time_bucketsClient[1]) +3600
[1] "2015-07-23 01:00:01 EDT"

Yet, if I insert in the array element it returns this

time_bucketsClient[1+1] <- as.POSIXct(time_bucketsClient[1]) +3600
time_bucketsClient[2]
[1] "1437627601"

the whole array has that number as a constant after the time_bin[1], which I set from a data frame value

Why is it doing this? How can I get the date and hour returned in each element of the array, increasing by an hour each time? I tried converting to asPOSIX.ct and using asDate, but it doesn't give me the right value.

Thanks.

Upvotes: 1

Views: 2033

Answers (1)

Gavin Simpson
Gavin Simpson

Reputation: 174813

You don't need a loop to do generate the time sequence, just use the seq method for objects of class POSIXt. For example, using the start date time:

tt <- as.POSIXct("2015-07-23 00:00:01")

A 24 hour sequence from the start date time can be produced using the seq method

tts <- seq(tt, by = "hours", length = 24)

> head(tts)
[1] "2015-07-23 00:00:01 CST" "2015-07-23 01:00:01 CST"
[3] "2015-07-23 02:00:01 CST" "2015-07-23 03:00:01 CST"
[5] "2015-07-23 04:00:01 CST" "2015-07-23 05:00:01 CST"

Then you would need to convert the sequence of date times into vectors of the dates and of the hour. For example, calling as.Date() on tts gets us a Date classed object of just the dates

head(as.Date(tts))

> head(as.Date(tts))
[1] "2015-07-23" "2015-07-23" "2015-07-23" "2015-07-23" "2015-07-23"
[6] "2015-07-23"

whereas a combination of as.numeric() and format() gets us the hour

as.numeric(format(tts, format = "%H"))

> as.numeric(format(tts, format = "%H"))
 [1]  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

Combining these steps is as easy as

df <- data.frame(Times = tts)
df <- transform(df,
                Date = as.Date(Times),
                Hour = as.numeric(format(Times, format = "%H")))

which gives

> head(df)
                Times       Date Hour
1 2015-07-23 00:00:01 2015-07-23    0
2 2015-07-23 01:00:01 2015-07-23    1
3 2015-07-23 02:00:01 2015-07-23    2
4 2015-07-23 03:00:01 2015-07-23    3
5 2015-07-23 04:00:01 2015-07-23    4
6 2015-07-23 05:00:01 2015-07-23    5

Upvotes: 3

Related Questions