1

I would like to convert a column of a dataframe into gregorian date. For example the following dataframe:

       Date_R Tmax
1  1985-01-01  9.0
2  1985-02-02  9.0
3  1985-12-31 11.0
4  1986-01-04  8.5
5  1986-01-05 11.0

Into:

  Date_R Tmax
1      1  9.0
2     33  9.0
3    365 11.0
4      4  8.5
5      5 11.0

Or add a new column with this information.

Thanks in advance

Ruben
  • 493
  • 4
  • 18
  • 2
    http://stackoverflow.com/questions/7958298/how-do-you-convert-posix-date-to-day-of-year-in-r – rmuc8 May 26 '15 at 11:17

2 Answers2

7

Convert the 'Date_R' column to 'Date' class (if not), and format with option %j to get the day of the year.

 df1$Date_R <- as.numeric(format(as.Date(df1$Date_R), '%j'))
 df1
 #  Date_R Tmax
 #1      1  9.0
 #2     33  9.0
 #3    365 11.0
 #4      4  8.5
 #5      5 11.0
akrun
  • 874,273
  • 37
  • 540
  • 662
7

Or you can use as.POSIXlt

as.POSIXlt(df$Date_R)$yday + 1L
## [1]   1  33 365   4   5
David Arenburg
  • 91,361
  • 17
  • 137
  • 196