简体   繁体   English

R:每日数据到每月

[英]R: Daily data to monthly

I have a large xts object, with multiple variable.我有一个大 xts object,有多个变量。 The index is daily in that manner, it corresponds to exact days, however there is only one observation for each variable in a month.该指数以这种方式每天显示,它对应于确切的日期,但是每个变量在一个月内只有一个观察值。 Is there a way to drop the day from the index and only keep year-month?有没有办法从索引中删除日期并只保留年月?

To ilustrate my problem for instance I have var1 with an observation on 2011-06-28 and var2 with observation 2011-06-30.例如,为了说明我的问题,我在 2011 年 6 月 28 日观察到 var1,在 2011 年 6 月 30 日观察到 var2。 I would like to index both as 2011-06我想将两者都索引为 2011-06

Thanks谢谢

You can probably do this: Use gsub (replace a pattern with whatever you want) with regex (a sequence of characters that define a search pattern in eg a string).您可能可以这样做:使用 gsub(用您想要的任何内容替换模式)和正则表达式(在例如字符串中定义搜索模式的字符序列)。 The pattern is done with regex, which has lots of metacharacters that allow you to do more advanced things.该模式是用正则表达式完成的,它有很多元字符,可以让你做更高级的事情。 The dot (.) is a wildcard and the $ anchors it at the back.点 (.) 是通配符,$ 将其锚定在后面。 So the pattern is basically any 3 characters before the end and replace them with nothing.所以模式基本上是结束前的任何 3 个字符,并且什么都不替换它们。

your_object<-c("2011-06-28","2011-06-30")
gsub(pattern = "...$", replace = "", x = your_object)

Here is a guide for using gsub with regex ( http://uc-r.github.io/regex ).这是使用 gsub 和正则表达式的指南( http://uc-r.github.io/regex )。

alternatively you could "tell" R that you are using dates of a certain format with the as.Date() function and then use format() to change it to the format you desire.或者,您可以“告诉” R 您正在使用带有as.Date() function 的特定格式的日期,然后使用format()将其更改为您想要的格式。 Like this:像这样:

dates=c("2011-06-28","2011-06-29","2011-06-30","2011-07-1") #test string with dates in original format

dates2 <- format(as.Date(dates,"%Y-%m-%d"), format="%Y-%m") #changing the "%Y-%m-%d" format to  the desired "%Y-%m"

print(dates2) 

Edit: If you only want to change the index of a xts: indexFormat(xts_object) <- "%Y-%m"编辑:如果您只想更改 xts 的索引: indexFormat(xts_object) <- "%Y-%m"

Cheers Chris干杯克里斯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM