Pregunta

Say if I have an array that contains 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"

and another array of hourly values:

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

How would I change the hours in DateTime to be equivalent to the hours in hour_vals, for example:

> 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"
¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top