从r中的datetime提取月和年

  • 本文关键字:提取 datetime 中的 r date
  • 更新时间 :
  • 英文 :


假设我有这个例子df dataset

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

我想提取月份和年份,像这样

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

解决方案吗?任何东西,可以使用润滑剂或任何东西

lubridatemonthyear将工作

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

如果您希望月份格式为Jan,请使用month.abbJanuary,请使用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

您可以使用format%B表示月,%Y表示年,或者使用months表示月。

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"

最新更新