How to convert date to YYYYDDD?

I cannot figure out how to turn Sys.Date () into a number in the format YYYYDDD. If DDD is the day of the year, that is, January 1 will be 2016,001 December 31 will be 2016365

Date <- Sys.Date() ## The Variable Date is created as 2016-01-01 SomeFunction(Date) ## Returns 2016001 
+5
source share
3 answers

You can simply use the format function as follows:

 format(Date, '%Y%j') 

which gives:

 [1] "2016161" "2016162" "2016163" 

If you want to format it in other ways, see ?strptime for all possible parameters.

Alternatively, you can use the year and yday from the data.table or lubridate and paste them together with paste0 :

 library(data.table) # or: library(lubridate) paste0(year(Date), yday(Date)) 

which will give you the same result.


The values ​​returned by both parameters have a class sign. Wrap the above solutions in as.numeric() to get real numbers.


Used data:

 > Date <- Sys.Date() + 1:3 > Date [1] "2016-06-09" "2016-06-10" "2016-06-11" > class(Date) [1] "Date" 
+6
source

Here is one parameter with lubridate :

 library(lubridate) x <- Sys.Date() #[1] "2016-06-08" paste0(year(x),yday(x)) #[1] "2016160" 
+3
source

This should work to create a new column with the specified date format:

 Date <- Sys.Date df$Month_Yr <- format(as.Date(df$Date), "%Y%d") 

But, especially when working with large data sets, it is easier to do the following:

 library(data.table) setDT(df)[,NewDate := format(as.Date(Date), "%Y%d" 

Hope this helps. You may need to change if you want only one value and are not working with a dataset.

+1
source

All Articles