从 R 中的日期提取月份和年份 [英] Extract Month and Year From Date in R

查看:44
本文介绍了从 R 中的日期提取月份和年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了很多方法都无济于事.我有日期 (YYYY-MM-DD) 方面的数据,并且我试图仅获取月份和年份,例如:MM-YYYY 或 YYYY-MM.

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.

推荐答案

这将使用指定的格式向您的 data.frame 添加一个新列.

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") )

一个简单的例子:

dates <- "2004-02-06"

format(as.Date(dates), "%Y-%m")
> "2004-02"

附注:如果您正在处理大型数据集,data.table 方法会更快.

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") ]

这篇关于从 R 中的日期提取月份和年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆