【问题标题】:Extract month and year from datetime in R [duplicate]从R中的日期时间提取月份和年份[重复]
【发布时间】:2021-11-04 02:58:40
【问题描述】:

假设我有这个示例 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

标签: r date


【解决方案1】:

lubridate monthyear 可以工作。

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

【讨论】:

  • 谢谢,你真好
【解决方案2】:

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

【讨论】:

  • 感谢您提供的信息:D
猜你喜欢
  • 2016-02-10
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-16
  • 2021-09-11
  • 2014-09-28
相关资源
最近更新 更多