0

This question has appeared before, I know, but I haven't been able to derive the correct output after running Sys.setlocale("LC_TIME", "american").

Ok, so I have dataframe with a column of dates that look something like "October 2020" and "June 2021", etc.

I run as.Date(dataframe$month_column, format = "%B %Y"), and I do this after running Sys.setlocale() with the above inputs. But my output continues to be a bunch of NAs.

I suppose one work around I could try would be to split the Month and Year parts by the space into two columns, which might make it easier to coerce into date types, but I'd like to avoid that if possible, since I want to plot quantities by Month Year.

Any insight would be appreciated.

Stanley Yu
  • 99
  • 5
  • 1
    `lubridate::my()` might be your friend here. –  Mar 04 '22 at 22:04
  • 1
    Dates in R need to be real *dates*, not just a month-year combo. R won't assume that you mean the beginning or end of the month, so you need to be explicit by pasting the day-of-month on each string. I suggest the first, all months have a 1: if `vec` is a vector of "Month Year", then use `as.Date(paste("1", vec), format = "%d %B %Y")`. – r2evans Mar 04 '22 at 22:14
  • You have to add day of the month as mentioned in help of function `strptime()`: "However, if a month is specified, the day of that month has to be specified by %d or %e since the current day of the month need not be valid for the specified month". So, this is a solution: `as.Date(paste("01", dataframe$month_column), format = "%d %B %Y")` – josep maria porrà Mar 04 '22 at 22:18

1 Answers1

2

You can convert character strings of month and years with the my() function in the lubridate package. my, in this case, stands for month-year (there are also other functions, like mdy() which look for entries in the form of month-day-year, and dym() which expect day-month-year order).

library(lubridate) 

dates <- data.frame(
  dt = c("October 2020", "June 2021")
)

dates$converted <-my(dates$dt) 

dates

Output:

            dt  converted
1 October 2020 2020-10-01
2    June 2021 2021-06-01
rdelrossi
  • 1,114
  • 1
  • 7
  • 17