Merge or cbind xts object with dataframe

こ雲淡風輕ζ 提交于 2019-12-11 10:30:51

问题


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)

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 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).

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.


回答1:


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"

while Date in df is of Date type.

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


来源:https://stackoverflow.com/questions/47939207/merge-or-cbind-xts-object-with-dataframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!