Home > Software design >  How can I create a Month-Day vector in R?
How can I create a Month-Day vector in R?

Time:12-10

I want to create a vector in R, which contains month abbreviation and date:

  • Jan1, Jan2, Jan3, ..., Dec29, Dec30, Dec31.

How can I create such a vector?

I have tried different approaches. Using paste0(month.abb,1:31) gives me a vector containing Jan1,Feb2,Mar3.

I also created 12 different vectors for each month (df_jan <- paste0("Jan",1:31) and so on). Then I attempted to rbind the 12 vectors, but that also doesn't help.

Can you suggest any way to do this?

CodePudding user response:

The solution is dependent on the year of the dates. A leap year would have Feb29 in it.

Here's a function which takes year as an argument and return dates in the required format.

monthday <- function(year) {
  format(seq(as.Date(paste0(year, '-01-01')), 
             as.Date(paste0(year, '-12-31')), by = 'day'), '%b%d')
}

monthday(2021)
# [1] "Jan01" "Jan02" "Jan03" "Jan04" "Jan05" "Jan06" "Jan07" "Jan08" "Jan09"
#...
#[55] "Feb24" "Feb25" "Feb26" "Feb27" "Feb28" "Mar01" "Mar02" "Mar03" "Mar04"
#....
#[361] "Dec27" "Dec28" "Dec29" "Dec30" "Dec31"


monthday(2020)
# [1] "Jan01" "Jan02" "Jan03" "Jan04" "Jan05" "Jan06" "Jan07" "Jan08" "Jan09"
#....
#[55] "Feb24" "Feb25" "Feb26" "Feb27" "Feb28" "Feb29" "Mar01" "Mar02" "Mar03"
#....
#[361] "Dec26" "Dec27" "Dec28" "Dec29" "Dec30" "Dec31"

CodePudding user response:

You can create a sequence of dates and convert it using format For more details on POSIX standard format use ?strptime

whole_year_dates <- seq.Date(as.Date("2021-01-01"), as.Date("2021-12-31"), by = "day")

whole_year_dates_abbr <- format(whole_year_dates, format= "%b%d")
  •  Tags:  
  • r
  • Related