本文介绍了合并或绑定XTS对象与数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含每月时间序列(各种金融和经济变量)的数据框,如下所示:

I have a dataframe with monthly time series (various financial and economic variables), something like this:

var1 <- c('1','2','3')
var2 <- c('1','2','3')
Date <- as.Date(c('1995-11-1','1995-12-1','1996-1-1'))
df <- data.frame(Date, var1, var2)

,我想添加一些其他要从FRED下载的变量,如下所示:

and I would like to add a number of further variables which I am downloading from FRED, like this:

library('quantmod')
y<-getSymbols('T10Y2Y',src='FRED', auto.assign=FALSE)
y2<-to.monthly(y)

y是一个"xts""zoo"对象.现在,y2的长度与我现有的数据帧的长度不同.将y2合并或绑定到数据框的最简单方法是什么,而仅保留数据框中的日期数(在上面的MinExample中,仅保留这3个月).

y is an "xts" "zoo" object. Now, y2 is of a different length than my existing dataframe. What would be the easiest way to merge or cbind the y2 to the dataframe, while only keeping the number of dates that are in the dataframe (in the MinExample above, keeping only those 3 months).

我尝试了merge(df,y2,by ='Date'),但是y2对象实际上没有日期,而是带有日期的索引.感谢您的任何建议.

I have tried merge(df, y2, by='Date') however the y2 object does not really have a date, rather an index with dates. I am thankful for any suggestions.

推荐答案

使用与df中相同的时间序列结构,将y2转换为data.frame(或将df转换为xts对象).请注意,原始时间序列结构不同:

Convert y2 to a data.frame (or convert df to an xts object), with the same time series structure as in df. Note that the original time series structures are different:

> class(index(y2))
[1] "yearmon"

,而df中的DateDate类型.

y2df <- data.frame(Date = as.Date(index(y2)), 
                   coredata(y2))

df <- merge(df, y2df, by = "Date")

#> df
#        Date var1 var2 y.Open y.High y.Low y.Close
#1 1995-11-01    1    1   0.46   0.50  0.40    0.40
#2 1995-12-01    2    2   0.39   0.45  0.33    0.40
#3 1996-01-01    3    3   0.42   0.67  0.41    0.67

这篇关于合并或绑定XTS对象与数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 08:35