2
votes

I would like to add an open price as a new row at the end of a "SPY" data frame that was produce using the quantmod package, I used the following code in order to rbind the new row but I got an error

# rm(list = ls())  # generally considered as bad manner in an MWE
require(quantmod)
options(scipen=999)
spy <- getSymbols(("SPY") , src = 'yahoo', from = '2016-01-01', auto.assign = T)
spy<-cbind(SPY)
tail(SPY)
           SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted
2016-01-14   189.55   193.26  187.66    191.93  240795600       191.93
2016-01-15   186.77   188.76  185.52    187.81  324846400       187.81
2016-01-19   189.96   190.11  186.20    188.06  190196000       188.06
2016-01-20   185.03   187.50  181.02    185.65  280016900       185.65
2016-01-21   186.21   188.87  184.64    186.69  189174000       186.69
2016-01-22   189.78   190.76  188.88    190.52  163849600       190.52

I would like to insert new row manually into the spy dataset, so I tried to create a new xts object and than to use an rbind function but I got an error after those lines :

q <- c("2016-01-25",100,200,200,200,200,200) # creating the data
colnames(q) <- colnames(SPY) # creating column names as in SPY

But I got an error:

Error in `colnames<-`(`*tmp*`, value = c("SPY.Open", "SPY.High", "SPY.Low",  : 
  attempt to set 'colnames' on an object with less than two dimensions # creating the column names

How can I add this hand made row on the data frame's top ?

1
q is a vector. A vector as no column names. You probably want q <- data.frame(100,200,200,200,200,200) But be careful with the class of q and SPY.user3710546
Hello @Pascal, I used your suggestion and than use the rbind but I got this error:s<-rbind(SPY,q) Warning message: In rbind(SPY, q) : number of columns of result is not a multiple of vector length (arg 2)mql4beginner
See my answer below.user3710546

1 Answers

2
votes

You probably want:

q <- data.frame(100,200,200,200,200,200)
colnames(q) <- colnames(SPY)
q <- xts(q, as.Date("2016-01-26"))
#            SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted
# 2016-01-26      100      200     200       200        200          200

class(SPY)
# [1] "xts" "zoo"
class(q)
# [1] "xts" "zoo"

tail(rbind(SPY, q))
#            SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted
# 2016-01-19   189.96   190.11  186.20    188.06  190196000       188.06
# 2016-01-20   185.03   187.50  181.02    185.65  280016900       185.65
# 2016-01-21   186.21   188.87  184.64    186.69  189174000       186.69
# 2016-01-22   189.78   190.76  188.88    190.52  163849600       190.52
# 2016-01-25   189.92   190.15  187.41    187.64  122676200       187.64
# 2016-01-26   100.00   200.00  200.00    200.00        200       200.00