How to overcome error:“attempt to set 'colnames' on an object with less than two dimension” in xts object

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

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:

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 


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