Thanks, @Hermes: The problem is caused by the call to ifelse(), which returns vector of formats that begins and ends with NA. (Run debug(custom_date_format2) before you run your plotting command, and you'll be able to inspect fmt. In debug mode, pressing 'Enter' steps through the code, and you can see object values in the 'Environment' tab in the upper right.)
To fix this, you can either define custom_date_format2() like this:
custom_date_format2<-function(x) {
fmt =ifelse(month(x)==1 & mday(x)==1, "%Y",
ifelse(month(x)%%2 != 0, "%b","%b")) #originally ""
fmt <- replace_na(fmt, '%b') # requires tidyr or tidyverse package
return (format(x,fmt))
}
or you can use the tidyverse equivalent, if_esle(), which allows you to explicitly deal with missing values:
custom_date_format2<-function(x) {
# requires dplyr or tidyverse package
fmt =if_else(month(x)==1 & mday(x)==1, "%Y", missing = '%b',
if_else(month(x)%%2 != 0, "%b","%b", missing = '%b'))
return (format(x,fmt))
}
but the one I prefer is:
custom_date_format2<-function(x) {
# requires dplyr or tidyverse package
fmt <-
case_when(
month(x) == 1 & mday(x) == 1 ~ "%Y", # first pass
TRUE ~ "%b" # last pass
)
return (format(x,fmt))
}
since case_when() avoids the need for nested if_esle() statements and allows for explicit treatment of any case you need to deal with.
I hope this helps.