如何克服错误:“尝试在小于二维的对象上设置‘列名’"在 xts 对象中 [英] How to overcome error:"attempt to set 'colnames' on an object with less than two dimension" in xts object

查看:18
本文介绍了如何克服错误:“尝试在小于二维的对象上设置‘列名’"在 xts 对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在使用 quantmod 包生成的SPY"数据帧的末尾添加一个开盘价作为新行,我使用以下代码来绑定新行,但出现错误

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

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

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 ?

推荐答案

您可能想要:

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

这篇关于如何克服错误:“尝试在小于二维的对象上设置‘列名’"在 xts 对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆