Can we somehow convert dates such as "November 2017", "December 2017" to date? I tried to import csv data, but received factor columns.
I tried the following code, but was not successful.
as.POSIXct(as.character(dat$Date), format = "%B %Y") 14 Answers
A POSIXct date needs the day of the month to be complete and valid.
You can add it to the date strings, then use the format "%B %Y %d" e.g. :
as.POSIXct(paste(as.character(dat$Date),"01"), format = "%B %Y %d") BTW, when you import a csv you can set stringsAsFactors=FALSE (as argument of functions) to obtain characters instead of factors.
The argument truncated does the job:
library(lubridate) myd("November 2017", truncated = 1) # "2017-11-01" 4A quick solution from lubridate package
dmy(paste("01", dat$Date)) 0A proposition with the zoo package:
Sys.setlocale("LC_TIME","English") #> [1] "English_United States.1252" zoo::as.yearmon("November 2017", '%B %Y') #> [1] "Nov 2017" zoo::as.Date(zoo::as.yearmon("November 2017", '%B %Y')) #> [1] "2017-11-01" Sys.setlocale("LC_TIME","French") #> [1] "French_France.1252" zoo::as.yearmon("Novembre 2017", '%B %Y') #> [1] "nov. 2017" # Created on 2021-02-03 by the reprex package (v0.3.0.9001) Regards,