How to extract Month from date in R
Solution 1:
?month
states:
Date-time must be a POSIXct, POSIXlt, Date, Period, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects.
Your object is a factor, not even a character vector (presumably because of stringsAsFactors = TRUE
). You have to convert your vector to some datetime class, for instance to POSIXlt
:
library(lubridate)
some_date <- c("01/02/1979", "03/04/1980")
month(as.POSIXlt(some_date, format="%d/%m/%Y"))
[1] 2 4
There's also a convenience function dmy
, that can do the same (tip proposed by @Henrik):
month(dmy(some_date))
[1] 2 4
Going even further, @IShouldBuyABoat gives another hint that dd/mm/yyyy character formats are accepted without any explicit casting:
month(some_date)
[1] 2 4
For a list of formats, see ?strptime
. You'll find that "standard unambiguous format" stands for
The default formats follow the rules of the ISO 8601 international standard which expresses a day as "2001-02-28" and a time as "14:01:02" using leading zeroes as here.
Solution 2:
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")
Solution 3:
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"
Solution 4:
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