0

假设我有一个包含 DateTimes 的数组:

> head(DateTime)
[1] "2010-04-23 13:00:00 UTC" "2010-04-23 14:00:00 UTC" "2010-04-23 15:00:00 UTC"
[4] "2010-04-23 16:00:00 UTC" "2010-04-23 17:00:00 UTC" "2010-04-23 18:00:00 UTC"

和另一个每小时值数组:

> head(hour_vals)
[1] 20 20 20 20 20 20

我如何将 DateTime 中的小时数更改为等于 hour_vals 中的小时数,例如:

> head(FinalResult)
[1] "2010-04-23 20:00:00 UTC" "2010-04-23 20:00:00 UTC" "2010-04-23 20:00:00 UTC"
[4] "2010-04-23 20:00:00 UTC" "2010-04-23 20:00:00 UTC" "2010-04-23 20:00:00 UTC"
4

1 回答 1

1

This is one way:

DateTime.lt <- as.POSIXlt(DateTime)
DateTime.lt$hour <- 20
DateTime <- as.POSIXct(DateTime.lt)

Unlike POSIXct, which stores datetimes as a single number (seconds since the epoch), POSIXlt stores them as tuples of seconds, minutes, hours, etc., which can be accessed directly (see ?POSIXlt for details). POSIXct has a smaller memory footprint, and is therefore the preferred datatype for datetime objects, but for tasks such as this, temporarily converting to POSIXlt is simple and effective.

于 2013-05-30T12:31:43.923 回答