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
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.
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() .
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))
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With