如何克服错误:"尝试设置' colnames'在一个小于二维的物体上#34;在xts对象中

时间:2016-01-26 09:07:11

标签: r xts

我想在" SPY"结束时添加一个开放价格作为新行。使用quantmod包生成的数据框,我使用以下代码来绑定新行,但是我收到了错误

# 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

我想在spy数据集中手动插入新行,所以我尝试创建一个新的xts对象,而不是使用rbind函数,但是在这些行后出现错误:

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

但我收到了一个错误:

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

如何在数据框的顶部添加这个手工制作的行?

1 个答案:

答案 0 :(得分:2)

你可能想要:

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