【发布时间】:2021-09-22 22:30:11
【问题描述】:
我经常得到几个xts 对象,其中日期作为行名。我必须将这些 xts 对象转换为 data.frame 对象,但是当我这样做时,作为日期的行名称将成为包含日期的名为 Ìndex 的新第一列。但我需要将那些Index 列称为Date。
因此,我想将所有新转换的data.frame 对象的第一列名称从Index 迭代更改为Date。
但是,当我尝试下面的(可重现的)代码时,在第 4 点,我系统地得到了一个 Error in `colnames<-`(`*tmp*`, value = `*vtmp*`) : attempt to set 'colnames' on an object with less than two dimensions
#**************#
# 1. Load data #
#**************#
library(fs)
library(quantmod)
library(zoo)
tickers <- c("NKLA", "MPNGF", "RMO", "JD", "COIN")
getSymbols.yahoo(tickers, auto.assign = TRUE, env = globalenv())
closeAllConnections()
#******************************#
# 2. Find all loaded xts files #
#******************************#
xtsObjects <- names(which(unlist(eapply(.GlobalEnv, is.xts))))
#******************************************************#
# 3. Convert into data.frames found xts files under 2. #
#******************************************************#
for (i in seq_along(xtsObjects)) {
assign(xtsObjects[i], fortify.zoo(get(xtsObjects[i])))
}
#***************************************************************#
# 4. Change name of 1st column to Date of converted xts objects #
#***************************************************************#
# Check if for loop prints what I want, as a precaution
for (i in seq_along(xtsObjects)) {
print(get(xtsObjects[i]))
}
# But when I try the following, I get the error shown above
for (i in seq_along(xtsObjects)) {
colnames(xtsObjects[i])[1] <- "Date"
}
# Same error here
for (i in seq_along(xtsObjects)) {
colnames(xtsObjects)[which(names(xtsObjects) == "Index")] <- "Date"
}
# Still same error
for (i in seq_along(xtsObjects)) {
colnames(xtsObjects)[colnames(xtsObjects) == "Index"] <- "Date"
}
我的问题:
- 我必须输入什么循环代码才能将所有新转换的
xts对象中的第一列Index更改为Date到data.frame对象?
使用的系统:
- R 版本:4.1.1 (2021-08-10)
- RStudio 版本:1.4.1717
- 操作系统:macOS Catalina 版本 10.15.7 和 macOS Big Sur 版本 11.6
【问题讨论】: