日期格式MMM-YYYY [英] Date formatting MMM-YYYY

查看:587
本文介绍了日期格式MMM-YYYY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期格式如下的数据集:

I have a dataset with dates in following format:

初始值:

Jan-2015 Apr-2013 Jun-2014 Jan-2015 Jan-2016 Jan-2015 Jan-2016 Jan-2015 Apr-2012 Nov-2012 Jun-2013 Sep-2013

最终:

Feb-2014 Jan-2013 Sep-2014 Apr-2013 Sep-2014 Mar-2013 Aug-2012 Apr-2012 Oct-2012 Oct-2013 Jun-2014 Oct-2013

我想执行以下步骤:


  1. 为月份和年份创建虚拟变量

  2. 将这些日期与另一个日期相减,以找出持续时间(最终缩写)(以月为单位)

想要在R中执行这些操作?

I would like to do these in R?

推荐答案

要扩展@neilfws答案,可以使用 month lubridate 包中的 year 函数用月和年创建虚拟变量在您的数据框中。

To expand on @neilfws answer, you can use the month and year functions from the lubridate package to create your dummy variables with the month and year in your data frame.

这是代码:

library(lubridate)
library(zoo)
df <- data.frame(Initial = c("Jan-2015", "Apr-2013", "Jun-2014", "Jan-2015", "Jan-2016", "Jan-2015", 
                         "Jan-2016", "Jan-2015", "Apr-2012", "Nov-2012", "Jun-2013", "Sep-2013"),
             Final = c("Feb-2014", "Jan-2013", "Sep-2014", "Apr-2013", "Sep-2014", "Mar-2013", 
                       "Aug-2012", "Apr-2012", "Oct-2012", "Oct-2013", "Jun-2014", "Oct-2013"))

df$Initial <- as.character(df$Initial)
df$Final <- as.character(df$Final)
df$Initial <- as.yearmon(df$Initial, "%b-%Y")
df$Final <- as.yearmon(df$Final, "%b-%Y")
df$month_initial <- month(df$Initial)
df$year_intial <- year(df$Initial)
df$month_final <- month(df$Final)
df$year_final <- year(df$Final)

df$Difference <- 12*(df$Initial-df$Final)

这是最后一个d ata.frame:

And here is the final data.frame:

> head(df)
   Initial    Final month_initial year_intial month_final year_final Difference
1 Jan 2015 Feb 2014             1        2015           2       2014         11
2 Apr 2013 Jan 2013             4        2013           1       2013          3
3 Jun 2014 Sep 2014             6        2014           9       2014         -3
4 Jan 2015 Apr 2013             1        2015           4       2013         21
5 Jan 2016 Sep 2014             1        2016           9       2014         16
6 Jan 2015 Mar 2013             1        2015           3       2013         22

希望这会有所帮助!

这篇关于日期格式MMM-YYYY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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