-5

I have dataframe with a column of dates of the form YYYY/MM, factor class, and I wish to convert it to date class. E.g. 2000/01 -> Jan 2000

I note that as.Date() is unable to handle date formats without the day component. I have tried using the as.yearmon() function from the zoo package.

library('zoo')   
as.yearmon(factor("2000-01"))  # It works with YYYY-MM format    
# [1] "Jan 2000"      
as.yearmon(factor("2000/01"))   
# [1] NA  
as.yearmon(factor("2000/01"),"%y/%m") 
# [1] NA

I'm looking for a function that will turn factor("2000/01") to "Jan 2000". Any help would be kindly appreciated.

Sathish
  • 12,453
  • 3
  • 41
  • 59

1 Answers1

1

If as.Date has a problem with the day of month not being present, then for your purposes you can temporarily feed it with any day:

# Generate 10 "YYYY/MM"
n <- 10
our_dates <- paste(sample(1000:2000, n), sample(11:12, n, replace = TRUE), sep = "/")
our_dates
[1] "1027/12" "1657/12" "1180/11" "1646/12" "1012/12" "1684/12" "1693/11" "1835/11"
[9] "1916/11" "1073/12"

# Dirty fix, add a "day of month" to our dates
our_dates <- paste0(our_dates, "/01")
our_dates
[1] "1027/12/01" "1657/12/01" "1180/11/01" "1646/12/01" "1012/12/01" "1684/12/01"
[7] "1693/11/01" "1835/11/01" "1916/11/01" "1073/12/01"

# Format as dates
x <- as.Date(our_dates,"%Y/%m/%d")

# Now print out in your fromat:
format(x, format = "%b %Y")
[1] "Dec 1027" "Dec 1657" "Nov 1180" "Dec 1646" "Dec 1012" "Dec 1684" "Nov 1693"
[8] "Nov 1835" "Nov 1916" "Dec 1073"
s_baldur
  • 29,441
  • 4
  • 36
  • 69