Search code examples
rdatedatetimelubridate

Convert day and month to number of the year (1 - 365) in R


Let's suppose I have a data frame with two columns, one for months and the second one for days. Here is a simple example

month=c(2, 4, ,7, 8, 11, 11, 12)
day=c(21,4,6,8,15,20,30)
monthday=data.frame(month,day)

I want to determine a number (from 1 to 365) that corresponds to the year's day. How can I do that?


Solution

  • You can use the yday function from the lubridate package:

    library(dplyr)
    library(tidyr)
    library(lubridate)
    
    month=c(2, 4,7, 8, 11, 11, 12)
    day=c(21,4,6,8,15,20,30)
    # also define a year so you can parse an actual date
    year = 2021
    monthday=tibble(month,day, year)
    
    monthday %>% 
      # combine into one variable
      tidyr::unite("date", year, month, day, sep = "-", remove = FALSE) %>% 
      # parse as date
      dplyr::mutate(date = lubridate::ymd(date)) %>% 
      # extract day of year
      dplyr::mutate(doy = lubridate::yday(date))
    
    #> # A tibble: 7 x 5
    #>   date       month   day  year   doy
    #>   <date>     <dbl> <dbl> <dbl> <dbl>
    #> 1 2021-02-21     2    21  2021    52
    #> 2 2021-04-04     4     4  2021    94
    #> 3 2021-07-06     7     6  2021   187
    #> 4 2021-08-08     8     8  2021   220
    #> 5 2021-11-15    11    15  2021   319
    #> 6 2021-11-20    11    20  2021   324
    #> 7 2021-12-30    12    30  2021   364
    

    Created on 2021-05-31 by the reprex package (v2.0.0)