R: Yearmon producing NA values

80 Views Asked by At

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!

4

There are 4 best solutions below

0
Quinten On BEST ANSWER

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

2
jpsmith On

You need to tell zoo::as.yearmon() what format your dates are in:

zoo::as.yearmon(my_df$var2, format = "%b-%y")

# [1] "Apr 2018" "May 2018" "Jun 2018"

Here, %b is the three letter month abbreviation, - indicates the the data-specific separator, and %y represents the 2-digit year.

2
Maël On

You don't seem to need as.yearmon, here; just use the right format in as.Date:

as.Date(do.call(paste, my_df), format = "%d %b-%y")
#[1] "2018-04-10" "2018-05-20" "2018-06-15"

Or like this, for plotting:

as.Date(paste("01", my_df$var2), format = "%d %b-%y")
#[1] "2018-04-01" "2018-05-01" "2018-06-01"

my_df$var2 <- as.Date(paste("01", my_df$var2), format = "%d %b-%y")
plot(my_df$var1, my_df$var2, type = "l")

enter image description here

0
G. Grothendieck On

It is not necessary to convert it to Date class to plot it. plot.zoo will plot yearmon data, autoplot.zoo will plot it using ggplot2 and xyplot.zoo will plot it using lattice. Note that the format of the data must be specified when converting to yearmon if not in the default format that as.yearmon assumes.

library(zoo)
my_df |>
  read.zoo(index = 2, FUN = as.yearmon, format = "%b-%y") |>
  plot(xlab = "", ylab = "")

or using ggplot2

library(ggplot2)
library(zoo)
my_df |>
  read.zoo(index = "var2", FUN = as.yearmon, format = "%b-%y") |>
  autoplot() + labs(x = "", y = "")

or using lattice

library(lattice)
library(zoo)
my_df |>
  read.zoo(index = "var2", FUN = as.yearmon, format = "%b-%y") |>
  xyplot(xlab = "", ylab = "")

The plot output looks like this. The others are similar but not identical.

screenshot