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

I am importing some data from NOAA and it has dates and times in separate columns. I was looking for an elegant way to add one datetime column to my R file, but couldn't. I found a question about stack exchange about the opposite, but not about that. Is there a simple as.Date command that I could run? I just use read.table for the downloaded text file, and it imports only find.

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

>yr mo dy hr mn degT ms ms1 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 
+6
source share
2 answers

You can use ISOdatetime , which is a simple wrapper for as.POSIXct . Remember to specify the sec argument as zero.

 Data$timestamp <- with(Data, ISOdatetime(YY,MM,DD,hh,mm,0)) 
+10
source

Yes, you want to insert date time columns together, and then force this complete row to the date object.

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

Assuming dat is an object containing buoy data. This adds new columns that are objects of the "POSIXlt" class, or you can use as.POSIXct() if you prefer a different format.

Or, by looking at the file, you can use the column names:

 dat <- within(dat, datetime <- as.POSIXlt(paste(YY, MM, DD, hh, mm), format = "%Y %m %d %H %M")) 
+5
source

Source: https://habr.com/ru/post/906211/


All Articles