从R中的日期时间中提取月份和年份

3

假设我有这个示例df数据集

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

有任何解决方案吗?可以使用lubridate或其他工具吗?


@DavidMakogon,感谢你为我挺身而出:D - Napier
2个回答

5
的和函数可用。
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.abb,如果想要格式为January,请使用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

谢谢,你真是太好了。 - Napier

3

您可以使用格式%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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接