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.
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).
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.
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.
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") ]
Use substring?
d = "2004-02-06" substr(d,0,7) >"2004-02"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With