Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dates and Times in separate columns, convert to datetime in R

Tags:

date

r

I am importing some data from NOAA and it has dates and times in separate columns. I searched for an elegant way to append a single datetime column in my R dataframe but was unable. I found a stack exchange question about the inverse but not this one. Is there a simple as.Date command I could run? I am simply using read.table for a downloaded text file and it imports just find.

Buoy data is here: http://www.ndbc.noaa.gov/data/realtime2/51202.txt

>yr mo  dy  hr  mn  degT    m.s m.s.1   m   sec sec.1 degT.1    hPa degC    degC.1  degC.2  nmi hPa.1   ft
>2012   1   16  3   55  MM  MM  MM  1.4 10  7.2 339 MM  MM  23.9    MM  MM  MM  MM
like image 238
David Pitkin Avatar asked Jan 17 '12 15:01

David Pitkin


People also ask

How do I convert a column to a datetime in R?

To convert a data frame column of type string into date/time in R, call as. POSIXct() function and pass the column as argument to this function. We may optionally pass time zone, date/time format, etc., to this function.

How do I separate days from date in R?

You can simply use weekdays(df$date) to extract the day of the week from the date. Only make sure the column is of type Date or convert using as. Date() .


2 Answers

You can use ISOdatetime, which is just a simple wrapper to as.POSIXct. Make sure to specify the sec argument as zero.

Data$timestamp <- with(Data, ISOdatetime(YY,MM,DD,hh,mm,0))
like image 135
Joshua Ulrich Avatar answered Nov 15 '22 13:11

Joshua Ulrich


Yep, you want to paste the date time columns together and then coerce that full string to a date time object.

dat <- within(dat, datetime <- as.POSIXlt(paste(yr, mo, dy, hr, mn),
                                          format = "%Y %m %d %H %M"))

assuming dat is the object containing the buoy data. This adds a new columns that is a "POSIXlt" class object or you could use as.POSIXct() if you prefer the other format.

Or, having looked at the file so can use their column names:

dat <- within(dat, datetime <- as.POSIXlt(paste(YY, MM, DD, hh, mm),
                                          format = "%Y %m %d %H %M"))
like image 43
Gavin Simpson Avatar answered Nov 15 '22 13:11

Gavin Simpson