R编程:使用for循环在数组中创建每小时的时间间隔 [英] R Programming: Create hourly time intervals in an array with for loop

查看:77
本文介绍了R编程:使用for循环在数组中创建每小时的时间间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的for循环,没有返回我需要的东西:

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"

方程式也返回时间

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"

整个数组在time_bin [1]之后有一个数字作为常量,我是根据数据帧值设置的

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

为什么要这样做?如何获得数组每个元素中返回的日期和小时,每次增加一个小时?我尝试转换为asPOSIX.ct并使用asDate,但它给我的值不正确.

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.

谢谢.

推荐答案

您不需要循环即可生成时间序列,只需对类的对象使用 seq 方法POSIXt .例如,使用开始日期时间:

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")

可以使用 seq 方法生成从开始日期时间起的24小时序列

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"

然后,您需要将日期时间序列转换为日期和小时的向量.例如,在 tts 上调用 as.Date()会得到一个仅包含日期的 Date 分类对象

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"

as.numeric() format()的组合为我们节省了时间

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

结合这些步骤就像

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

给出

> 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

这篇关于R编程:使用for循环在数组中创建每小时的时间间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆