Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract Month from date in R

Tags:

r

lubridate

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.

like image 964
apTNow Avatar asked Mar 24 '14 07:03

apTNow


People also ask

How do I get the month of the year in R?

The mdy() function flexibly converts date values supplied as month, then day, then year. The dmy() function flexibly converts date values supplied as day, then month, then year. Once the values are in class Date, R will by default display them in the standard format, which is YYYY-MM-DD.

How do you extract month and year from POSIXct in R?

For example, here's how to extract the year from a date: 1) date <- as. POSIXct("02/03/2014 10:41:00", format = "%m/%d/%Y %H:%M:%S) , and 2) format(date, format="%Y") . Now, you know how to use R to extract year from date.


1 Answers

?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.

like image 72
tonytonov Avatar answered Sep 21 '22 03:09

tonytonov