2

Here's my data which has 10 years in one column and 365 day of another year in second column

dat <- data.frame(year = rep(1980:1989, each = 365), doy= rep(1:365, times = 10))

I am assuming all years are non-leap years i.e. they have 365 days.

I want to create another column month which is basically month of the year the day belongs to.

library(dplyr)

dat %>% 
   mutate(month = as.integer(ceiling(day/31)))

However, this solution is wrong since it assigns wrong months to days. I am looking for a dplyr solution possibly.

h3rm4n
  • 4,126
  • 15
  • 21
89_Simple
  • 3,393
  • 3
  • 39
  • 94

2 Answers2

1

We can convert it to to datetime class by using the appropriate format (i.e. %Y %j) and then extract the month with format

dat$month <- with(dat, format(strptime(paste(year, doy), format = "%Y %j"), '%m'))

Or use $mon to extract the month and add 1

dat$month <- with(dat, strptime(paste(year, doy), format = "%Y %j")$mon + 1)
tail(dat$month)
#[1] 12 12 12 12 12 12
akrun
  • 874,273
  • 37
  • 540
  • 662
1

This should give you an integer value for the months:

dat$month.num <- month(as.Date(paste(dat$year, dat$doy), '%Y %j'))

If you want the month names:

dat$month.names <- month.name[month(as.Date(paste(dat$year, dat$doy), '%Y %j'))]

The result (only showing a few rows):

> dat[29:33,]
   year doy month.num month.names
29 1980  29         1     January
30 1980  30         1     January
31 1980  31         1     January
32 1980  32         2    February
33 1980  33         2    February
h3rm4n
  • 4,126
  • 15
  • 21