B. Davis
B. Davis

Reputation: 3441

convert day-number within the year to month/day format

I am trying to convert a day-number within the year to month/day format.

With this df:

set.seed(123)
df1 <- data.frame(Year = rep(15,100), DayNum = seq(78,177,1), Hour = sample(0:23,100,replace = T))
df2 <- data.frame(Year = rep(16,100), DayNum = seq(78,177,1), Hour = sample(0:23,100,replace = T))

df <- rbind(df1, df2)
> head(df)
  Year DayNum Hour
1   15     78    6
2   15     79   18
3   15     80    9
4   15     81   21
5   15     82   22
6   15     83    1
> tail(df)
    Year DayNum Hour
195   16    172   22
196   16    173   11
197   16    174    9
198   16    175   15
199   16    176    3
200   16    177   13

which has 100 records for 2015 and 2016, how can I make a POSIXct date/time column?

While there are a number of related posts with a Julian date from a beginning origin (usually 1970-01-01), I could not find any posts with a day-number within a year and with a variable year (i.e. 2015 and 2016).

Upvotes: 1

Views: 1334

Answers (2)

Dave2e
Dave2e

Reputation: 24109

The as.POSIXct function has an option to specify the origin date when converting from a "Julian" date to the date/time object:

#calculate the origin date based on the year column
df$origin<-as.Date(paste0("20", df$Year,"-01-01"))
#convert the Julian day to a date/time object
as.POSIXct(df$JulianDay, origin=df$origin)

One may need to consider adding the timezone option for completeness:

 as.POSIXct(df$JulianDay, origin=df$origin, tz="GMT")

Upvotes: 2

akuiper
akuiper

Reputation: 215067

You might need something like this, use %j to specify the day of the year:

strptime(with(df, paste(Year, DayNum, Hour)), "%y %j %H")

# [1] "2015-03-19 06:00:00 EDT"
# [2] "2015-03-20 18:00:00 EDT"
# [3] "2015-03-21 09:00:00 EDT"
# [4] "2015-03-22 21:00:00 EDT"
# [5] "2015-03-23 22:00:00 EDT"

Upvotes: 1

Related Questions