How to create a datetime object from separate date fields?

I have a dataset like this:

    Year MM DD HH
158 2010  7  1  5
159 2010  7  1  5
160 2010  7  1  6
161 2010  7  1  6

structure(list(Year = c(2010L, 2010L, 2010L, 2010L), MM = c(7L, 
7L, 7L, 7L), DD = c(1L, 1L, 1L, 1L), HH = c(5L, 5L, 6L, 6L)), .Names = c("Year", 
"MM", "DD", "HH"), row.names = 158:161, class = "data.frame")

How can I create a single datetime object from this dataset (new column for this data)?

+5
source share
3 answers

There are several options, here is one (where xis your data.frame):

x$datetime <- ISOdatetime(x$Year, x$MM, x$DD, x$HH, 0, 0)

If necessary, you can in the correct time zone, see ?ISOdatetime.

+7
source

Assuming you have data in a data frame x:

transform(x,datetime = as.POSIXct(paste(paste(Year,MM,DD,sep="-"), paste(HH,"00",sep=":"))))
    Year MM DD HH            datetime
158 2010  7  1  5 2010-07-01 05:00:00
159 2010  7  1  5 2010-07-01 05:00:00
160 2010  7  1  6 2010-07-01 06:00:00
161 2010  7  1  6 2010-07-01 06:00:00
+2
source

Now you can do it in lubridate with make_dateor make_datetime:

From cran doc doc:

make_datetime(year = 1970L, month = 1L, day = 1L, hour = 0L, min = 0L,
sec = 0, tz = "UTC")

make_date(year = 1970L, month = 1L, day = 1L)
+1
source

All Articles