Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading