Home > Back-end >  chr NAs appearing when creating dynamic date objects
chr NAs appearing when creating dynamic date objects

Time:01-31

I've got a very intermittent problem when creating some dynamic date objects.

library(lubridate)
day <- as.Date(Sys.time())
this_m <- format(day,"%m")
next_m <- format(day   months(1), "%m")
m_after <- format(day   months(2), "%m")

For some reason the next_m object delivers an object that is considered 'chr NA' while the m_after object delivers the correct value (as of today, a character object of "03"). This seems very strange to me, does anyone know why this might be?

EDIT: Ideally I'm create an object that has the numeric version of the month in two digits, e.g March is 03 rather than just 3

CodePudding user response:

With lubridate lingo

library(lubridate)

day <- today()
this_m  <- month(day)
next_m  <- month(day %m % months(1))
m_after <- month(day %m % months(2))

CodePudding user response:

you need to create a character vector to keep a leading 0

month_with_leading_0 <- ifelse(test=seq(12)<10, 
                               yes=paste0("0", month(day) months(seq(12)-1)@month), 
                               no=month(day) months(seq(12)-1)@month)

CodePudding user response:

So I was able to fix doing the following:

next_m  <- month(day %m % months(1), "%m")
m_after <- month(day %m % months(2), "%m")
  • Related