Home > other >  Extract month and year from datetime in R [duplicate]
Extract month and year from datetime in R [duplicate]

Time:09-17

Let's say I have this example df dataset

Order.Date       
2011-10-20       
2011-12-25       
2012-04-15      
2012-08-23       
2013-09-25       

I want to extract the month and the year, and be like this

Order.Date       Month       Year
2011-10-20       October     2011
2011-12-25       December    2011
2012-04-15       April       2012
2012-08-23       August      2012
2013-09-25       September   2013

any solution? anything, can use lubridate or anything

CodePudding user response:

lubridate month and year will work.

as.data.frame(Order.Date) %>%
  mutate(Month = lubridate::month(Order.Date, label = FALSE),
         Year = lubridate::year(Order.Date))

  Order.Date Month Year
1 2011-10-20    10 2011
2 2011-12-25    12 2011
3 2012-04-15     4 2012
4 2012-08-23     8 2012
5 2013-09-25     9 2013

If you want month format as Jan, use month.abb and as January, use month.name

as.data.frame(Order.Date) %>%
  mutate(Month = month.abb[lubridate::month(Order.Date, label = TRUE)],
         Year = lubridate::year(Order.Date))

  Order.Date Month Year
1 2011-10-20   Oct 2011
2 2011-12-25   Dec 2011
3 2012-04-15   Apr 2012
4 2012-08-23   Aug 2012
5 2013-09-25   Sep 2013

as.data.frame(Order.Date) %>%
  mutate(Month = month.name[lubridate::month(Order.Date, label = TRUE)],
         Year = lubridate::year(Order.Date))

  Order.Date     Month Year
1 2011-10-20   October 2011
2 2011-12-25  December 2011
3 2012-04-15     April 2012
4 2012-08-23    August 2012
5 2013-09-25 September 2013

CodePudding user response:

You can use format with %B for Month and %Y for Year or using months for Month.

format(as.Date("2011-10-20"), "%B")
#months(as.Date("2011-10-20")) #Alternative
#[1] "October"

format(as.Date("2011-10-20"), "%Y")
#[1] "2011"
  • Related