Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date-time conversion in R

I have created a file something like this:

> filesInside
         Date         Time
1  01:09:2013 10:35:49.997 
2  01:09:2013 10:35:50.197

How could I possibly make a function using

as.POSIXct()

and I should be get something like this:

> as.POSIXct("2013-09-01 10:35:50")
[1] "2013-09-01 10:35:50 NZST" 

How can I make it as a function?

My code so far:

DateTime <- as.POSIXct(paste(filesInside$Date, filesInside$Time), format="%Y%m%d %H%M%S")

Appreciate a bit of help please. Cheers

like image 969
jeff1234 Avatar asked Oct 24 '13 23:10

jeff1234


People also ask

How does R handle date and time data?

R provides several options for dealing with date and date/time data. The builtin as. Date function handles dates (without times); the contributed library chron handles dates and times, but does not control for time zones; and the POSIXct and POSIXlt classes allow for dates and times with control for time zones.

What does Lubridate do in R?

Lubridate is an R package that makes it easier to work with dates and times.


2 Answers

You may try this. The order of date-time components and separators in format should reflect those in the object to be converted. See also ?strptime.

with(filesInside,
     as.POSIXct(paste(Date, Time),
                format = "%d:%m:%Y %H:%M:%S",
                tz = "NZ"))
# [1] "2013-09-01 10:35:49 NZST" "2013-09-01 10:35:50 NZST"
like image 76
Henrik Avatar answered Oct 19 '22 05:10

Henrik


library(lubridate)
dmy_hms(apply(filesInside, 1, paste, collapse=" "), tz="NZ")
# [1] "2013-09-01 10:35:49 NZST" "2013-09-01 10:35:50 NZST"

lubridate here is a cinch, especially with its collection of dmy_hms, ymd etc functions.

To properly paste across rows, simply use apply(<data.frame>, 1, paste, collapse=" ")

like image 26
Ricardo Saporta Avatar answered Oct 19 '22 04:10

Ricardo Saporta