[r] How to extract Month from date in R

I am using the lubridate package and applying the month function to extract month from date. I ran the str command on date field and I got

Factor w/ 9498 levels "01/01/1979","01/01/1980",..: 5305 1 1 1 1 1 1 1 1 1 ...

> v1$Date<-month(v1$Date)
Error in as.POSIXlt.character(as.character(x), ...) : 
character string is not in a standard unambiguous format

Here is an example of my data frame

https://drive.google.com/file/d/0B6cqWmwsEk20Q2dHblhXZi14Wk0/edit?usp=sharing

I don't know what I am doing wrong.

This question is related to r lubridate

The answer is


For some time now, you can also only rely on the data.table package and its IDate class plus associated functions. (Check ?as.IDate()). So, no need to additionally install lubridate.

require(data.table)

some_date <- c("01/02/1979", "03/04/1980")
month(as.IDate(some_date, '%d/%m/%Y')) # all data.table functions

Her is another R base approach:

From your example: Some date:

Some_date<-"01/01/1979"

We tell R, "That is a Date"

Some_date<-as.Date(Some_date)

We extract the month:

months(Some_date)

output: [1] "January"

Finally, we can convert it to a numerical variable:

as.numeric(as.factor(months(Some_date)))

outpt: [1] 1

you can convert it into date format by-

new_date<- as.Date(old_date, "%m/%d/%Y")} 

from new_date, you can get the month by strftime()

month<- strftime(new_date, "%m")

old_date<- "01/01/1979"
new_date<- as.Date(old_date, "%m/%d/%Y")
new_date
#[1] "1979-01-01"
month<- strftime(new_date,"%m")
month
#[1] "01"
year<- strftime(new_date, "%Y")
year
#[1] "1979"

Without the need of an external package:

if your date is in the following format:

myDate = as.POSIXct("2013-01-01")

Then to get the month number:

format(myDate,"%m")

And to get the month string:

format(myDate,"%B")