Search code examples
rlubridatezoo

as.yearmon(dates, format = "%b/%Y") return NAs


I have run this code in RStudio:

library(zoo)
dates <- c("Sep/2012", "Aug/2012", "Jul/2012")
dates1 <- as.yearmon(dates, format="%b/%Y")
dates1

But it returns NAs:

[1] NA NA NA

I'm wondering why this is happening? In this post, it seems that this code returns normal results. Thanks.


Solution

  • Either set the locale to English as mentioned in the comments or else use the built-in month.abb vector which is always in English regardless of locale.

    Regarding the second alternative, use read.table to create a two column data frame from dates and then match the month column, V1, against month.abb to get the corresponding month number, paste that back together with the year, V2, and pass that to as.yearmon

    library(zoo)
    
    dates |>
      read.table(text = _, sep = "/") |>
      with(paste(V2, match(V1, month.abb), sep = "-")) |>
      as.yearmon()
    ## [1] "Sep 2012" "Aug 2012" "Jul 2012"
    

    or slightly shorter using gsubfn which matches the first 3 characters and replaces that with the output of the function given in formula notation in its second argument.

    library(gsubfn)
    library(zoo)
    
    dates |>
      gsubfn("^...", x ~ match(x, month.abb), x = _) |>
      as.yearmon("%m/%Y")
    ## [1] "Sep 2012" "Aug 2012" "Jul 2012"