问题
I am using quantmod which generates XTS objects with ticker info, and I am looking to compile/stack a bunch of XTS documents on top of each other to process code. Using Rbind with XTS I find that it does not stack XTS on top of each other, rather it merges and sorts by date:
x <- xts(1:10, Sys.Date()+1:10)
x
[,1]
2014-07-10 1
2014-07-11 2
2014-07-12 3
2014-07-13 4
2014-07-14 5
2014-07-15 6
2014-07-16 7
2014-07-17 8
2014-07-18 9
2014-07-19 10
y <- xts(rep(2,3), Sys.Date()+c(1,2,3))
y
[,1]
2014-07-10 2
2014-07-11 2
2014-07-12 2
rbind(x,y)
[,1]
2014-07-10 1
2014-07-10 2
2014-07-11 2
2014-07-11 2
2014-07-12 3
2014-07-12 2
2014-07-13 4
2014-07-14 5
2014-07-15 6
2014-07-16 7
2014-07-17 8
2014-07-18 9
2014-07-19 10
Warning message: In rbind(deparse.level, ...) : mismatched types: converting objects to numeric
Question 1 - Why is there a warning message?
Question 2 - How can I stack the XTS properly, probably a newbie question, but need the bind to look like this:
2014-07-10 1
2014-07-11 2
2014-07-12 3
2014-07-13 4
2014-07-14 5
2014-07-15 6
2014-07-16 7
2014-07-17 8
2014-07-18 9
2014-07-19 10
2014-07-10 2
2014-07-11 2
2014-07-12 2
回答1:
1) x
is integer; y
is numeric. xts objects are a matrix with an ordered index attribute. You can't mix types in a matrix, so x
is converted to numeric.
2) You can't. xts is a time series class. It would be very bad and confusing if xts allowed your data to not be sorted by time.
回答2:
xts
is a time series object derived from zoo
. It is simply a matrix object indexed by time. using rbind
between two xts
objects will sort them by time.
If you want to stack them one above the other you should work only with their coredata
which is the matrix
object.
datax = coredata(x)
datay = coredata(y)
rbinding = rbind(datax, datay)
You will lose the time info though. I don't know what is your porpouse here But that should do the trick.
If you want to "keep" the info of the xts object the data comes from you could use merge instead and it will create a column of the ticker you are working with, but with the data in the right time position.
merge(x, y, join = "outer", fill = NA)
来源:https://stackoverflow.com/questions/24661145/rbind-with-xts-how-to-stack-without-sorting-by-index-date