Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract Month and Year From Date in R

Tags:

date

r

I have tried a number of methods to no avail. I have data in terms of a date (YYYY-MM-DD) and am trying to get in terms of just the month and year, such as: MM-YYYY or YYYY-MM.

Ultimately, I would like it to look like this:

ID    Date         Month_Yr 1     2004-02-06   2004-02 2     2006-03-14   2006-03 3     2007-07-16   2007-07 ...   ...          ... 

I am doing this in hopes of plotting money earned on average in a month, from a number of orders, over a period of time. Any help, or a push in the right direction would be much appreciated.

like image 224
a.powell Avatar asked Jun 08 '16 13:06

a.powell


People also ask

How do I convert a date to month and year in R?

To convert a Date column to Month-year format, we suggest you use the function as. yearmon() from the zoo package. This converts the date to class “yearmon” and retains the proper ordering. In contrast, using format(column, "%Y %B") will convert to class Character and will order the values alphabetically (incorrectly).

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.

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

In Order to get month year from date in R we will be using Format() function. Let's see how to get month year from date in R with an example. Let's first create the dataframe. Month year is extracted from Date_of_birth column using Format() functions as shown below.


2 Answers

This will add a new column to your data.frame with the specified format.

df$Month_Yr <- format(as.Date(df$Date), "%Y-%m")  df #>   ID       Date Month_Yr #> 1  1 2004-02-06  2004-02 #> 2  2 2006-03-14  2006-03 #> 3  3 2007-07-16  2007-07  # your data sample   df <- data.frame( ID=1:3,Date = c("2004-02-06" , "2006-03-14" , "2007-07-16") ) 

a simple example:

dates <- "2004-02-06"  format(as.Date(dates), "%Y-%m") > "2004-02" 

side note: the data.table approach can be quite faster in case you're working with a big dataset.

library(data.table) setDT(df)[, Month_Yr := format(as.Date(Date), "%Y-%m") ] 
like image 93
rafa.pereira Avatar answered Oct 05 '22 05:10

rafa.pereira


Use substring?

d = "2004-02-06" substr(d,0,7) >"2004-02" 
like image 34
Allen Huang Avatar answered Oct 05 '22 04:10

Allen Huang