从R中的日期中提取月份和年份 [英] Extract Month and Year From Date in R
本文介绍了从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
添加新列
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"
边注:
<如果使用大型数据集,code> data.table 方法可能会更快。
library(data.table)
setDT(df)[, Month_Yr := format(as.Date(Date), "%Y-%m") ]
这篇关于从R中的日期中提取月份和年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文