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

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

A quick solution from lubridate package

dmy(paste("01", dat$Date)) 
0

A 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,

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.