adkane
adkane

Reputation: 1441

Changing to Date Format in R

I have a data column called month which I want to convert into date format

In the spreadsheet, it's of the form Mar-07

But when I try to convert it in R using:

mydata$month<-as.Date(mydata$month, format = "%b-%y")

I get NAs

Where am I going wrong? Thanks

Upvotes: 0

Views: 406

Answers (2)

Henrik
Henrik

Reputation: 67778

The zoo package has a class, yearmon, which can represent monthly data. There is an as.Date method for this class.

library(zoo)

ym <- as.yearmon("Mar-07", "%b-%y")
str(ym)
# Class 'yearmon'  num 2007

Convert yearmon object to class Date:

date <- as.Date(ym)
date
# [1] "2007-03-01"

str(date)
# Date[1:1], format: "2007-03-01"

The frac argument can be used to indicate a fraction of the month. The default frac is 0, i.e. first day in month, as above.

as.Date(ym, frac = 0.5)
# [1] "2007-03-16"

as.Date(ym, frac = 1)
# [1] "2007-03-31"

Upvotes: 2

BrodieG
BrodieG

Reputation: 52637

Here is a workaround:

dts <- paste(c("Jan", "Feb", "Mar"), "07", sep="-")
# [1] "Jan-07" "Feb-07" "Mar-07"
as.Date(paste0("1", dts), format = "%d%b-%y")
# [1] "2007-01-01" "2007-02-01" "2007-03-01"

Upvotes: 1

Related Questions