Creating a single timestamp from separate DAY OF YEAR, Year and Time columns in R
-
25-07-2021 - |
Вопрос
I have a time series dataset for several meteorological variables. The time data is logged in three separate columns:
- Year (e.g. 2012)
- Day of year (e.g. 261 representing 17-September in a Leap Year)
- Hrs:Mins (e.g. 1610)
Is there a way I can merge the three columns to create a single timestamp in R? I'm not very familiar with how R deals with the Day of Year variable.
Thanks for any help with this!
Решение
It looks like the timeDate
package can handle gregorian time frames. I haven't used it personally but it looks straightforward. There is a shift
argument in some methods that allow you to set the offset from your data.
http://cran.r-project.org/web/packages/timeDate/timeDate.pdf
Because you mentioned it, I thought I'd show the actual code to merge together separate columns. When you have the values you need in separate columns you can use paste
to bring them together and lubridate::mdy
to parse them.
library(lubridate)
col.month <- "Jan"
col.year <- "2012"
col.day <- "23"
date <- mdy(paste(col.month, col.day, col.year, sep = "-"))
Lubridate is a great package, here's the official page: https://github.com/hadley/lubridate
And here is a nice set of examples: http://www.r-statistics.com/2012/03/do-more-with-dates-and-times-in-r-with-lubridate-1-1-0/
Другие советы
You should get quite far using ISOdatetime
. This function takes vectors of year
, day
, hour
, and minute
as input and outputs an POSIXct
object which represents time. You just have to split the third column into two separate hour
minute
columns and you can use the function.