将yearmon列转换为R中的月份的最后一个日期 [英] Converting yearmon column to last date of the month in R

查看:84
本文介绍了将yearmon列转换为R中的月份的最后一个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据帧(df),如下所示:

I have a data frame (df) like the following:

Date        Arrivals

2014-07      100
2014-08      150
2014-09      200

我知道我可以将yearmon日期转换为每个月的第一个日期,如下所示:

I know that I can convert the yearmon dates to the first date of each month as follows:

df$Date <- as.POSIXct(paste0(as.character(df[,1]),"-01"), format = "%Y-%m-%d")

但是,由于我的数据要到月底才可用,因此我想将其索引到末尾而不是开始,因此我无法弄清楚.任何帮助表示赞赏.

However, given that my data is not available until the end of the month I want to index it to the end rather than the beginning, and I cannot figure it out. Any help appreciated.

推荐答案

如果Date变量是实际的yearmon类向量,则从 zoo 包中使用as.Date.yearmon方法可以通过其参数frac进行所需的操作.

If the Date variable is an actual yearmon class vector, from the zoo package, the as.Date.yearmon method can do what you want via its argument frac.

使用您的数据,并假设Date最初是字符向量

Using your data, and assuming that the Date was originally a character vector

library("zoo")
df <- data.frame(Date = c("2014-07", "2014-08", "2014-09"),
                 Arrivals = c(100, 150, 200))

我将其转换为yearmon向量:

df <- transform(df, Date2 = as.yearmon(Date))

假设这是您所拥有的,那么您可以将as.Date()frac = 1结合使用来实现所需的目标:

Assuming this is what you have, then you can achieve what you want using as.Date() with frac = 1:

df <- transform(df, Date3 = as.Date(Date2, frac = 1))

给出:

> df
     Date Arrivals    Date2      Date3
1 2014-07      100 Jul 2014 2014-07-31
2 2014-08      150 Aug 2014 2014-08-31
3 2014-09      200 Sep 2014 2014-09-30

这显示了各个步骤.如果您只想要最终的Date,则这是单线的

That shows the individual steps. If you only want the final Date this is a one-liner

## assuming `Date` is a `yearmon` object
df <- transform(df, Date = as.Date(Date, frac = 1))
## or if not a `yearmon`
df <- transform(df, Date = as.Date(as.yearmon(Date), frac = 1))

当从yearmon对象转换为Date对象时,参数参数frac以月份的分数表示,以分配给结果日期.因此,要获得每月的第一天,而不是像您的Question所示那样转换为字符并粘贴在"-01"上,最好使用frac = 0强制为Date对象.

The argument frac in the fraction of the month to assign to the resulting dates when converting from yearmon objects to Date objects. Hence, to get the first day of the month, rather than convert to a character and paste on "-01" as your Question showed, it's better to coerce to a Date object with frac = 0.

如果df中的Date不是yearmon类对象,则可以通过将其转换为1,然后使用如上所述的as.Date()方法来解决问题.

If the Date in your df is not a yearmon class object, then you can solve your problem by converting it to one and then using the as.Date() method as described above.

这篇关于将yearmon列转换为R中的月份的最后一个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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