rdatenazoo

R: Yearmon producing NA values


I am working with the R programming language.

I have data in the following form (May-18 = May 2018):

my_df = data.frame(
var1 = c(10,20,15),
var2 = c("Apr-18", "May-18", "Jun-18"))

Using this post (Convert month year to a date in r), I am trying to convert var2 into a date format for plotting e.g. plot(my_df$var1, my_df$var2, type = "l")

library(zoo)
as.Date(as.yearmon(my_df$var2))

But I get this error:

[1] NA NA NA

Can someone please show me a way to fix this error?

Thanks!


Solution

  • You could use the right abbreviations %b-%y to your as.yearmon function like this:

    my_df = data.frame(
      var1 = c(10,20,15),
      var2 = c("Apr-18", "May-18", "Jun-18"))
    
    library(zoo)
    my_df$var2 = as.Date(as.yearmon(my_df$var2, "%b-%y"))
    
    plot(my_df$var1, my_df$var2, type = "l")
    

    Created on 2023-10-24 with reprex v2.0.2