R code to rename header of an xts object using name(object) <- vector

旧巷老猫 提交于 2021-02-19 05:38:08

问题


I'm new to learning R and I'm having an issue with some of my R code. I placed all the code for your convenience so that you can see the logic in what I am trying to do. My issue is renaming the header of my xts object Monthly_Quotes. I understand that when having an invalid stock symbol, the getsymbols function will not retrieve the quotes for "zzzz", which is why I am running into the issue of renaming the header. I'd like to resolve this such that if I have a much larger list of ticker symbols that do not get downloaded, that I won't have an issue renaming the header from my list of ticker_symbols.

#Environment to store stock symbols data
ETF_Data <- new.env()

#Dates needed for getSymbols function
sDate <- as.Date("2007-09-04") #Start Date
eDate <- as.Date("2014-09-02") #End   Date

#Assign vector of ticker symbols
ticker_symbol <- c("zzzz","IVW","JKE","QQQ","SPYG","VUG" )

#Load functions  
source("Functions.R")

#Create empty list
Temp_ETF_Data <- list()

#Variable is a connection to a specific file that appends the output to the file
connection_string <- file("Log_File.txt", open = "wt")

#Sink allows the R output to a connection file which is connection_string
#Log_File.txt is created to the directory that has been set
sink(connection_string, type="message")

#Loop to retrieve prices from Yahoo's API and assign only the Adjusted column to the list.
for(i in ticker_symbol){  
  tryCatch(
  {
      getSymbols(i, env = ETF_Data, from = sDate, to = eDate, src = "yahoo", warning = FALSE) 
      Temp_ETF_Data[[i]] <- Ad(ETF_Data[[i]])
  },    

  error = function(e) {
      message("-ERROR-")
      message(paste("Error for ticker symbol  :", i, "\n"))
      message("Here's the original error message: ")
      message(e)
      message("")
      return(i)},
 finally = {
     message(paste("Data was processed for symbol:", "[", i, "]" ))
     message("\n","******************************************", "\n")  
}) 
}

#Turns off message once it is on the console and reads the line. 
#Then it closes the sink connection and closes the connection to the Log_File.txt
sink(type = "message")
readLines("Log_File.txt")
close(connection_string)

#Merge list into columns from list 
Daily_Quotes <- do.call(merge, Temp_ETF_Data)

#Create new xts object with the 1st trading day price of each month and assign column headers 
Monthly_Quotes  <- Daily_Quotes[startpoints(Daily_Quotes,'months')]
#This piece of code creates this error
#     "Error in `colnames<-`(`*tmp*`, value = c("zzzz", "IVW", "JKE", "QQQ",  : 
#         length of 'dimnames' [2] not equal to array extent"
names(Monthly_Quotes) <- c(ticker_symbol)

I tried this:

ticker_symbol <- colnames(Monthly_Quotes)
names(Monthly_Quotes) <- c(ticker_symbol)


回答1:


This does not directly answer your question (see the comment), but wouldn't this be easier:

library(quantmod)
ticker_symbol <- c("zzzz","IVW","JKE","QQQ","SPYG","VUG" )
sDate <- as.Date("2007-09-04") #Start Date
eDate <- as.Date("2014-09-02") #End   Date

get.symbol <- function(ticker) {  
  tryCatch(temp <- Ad(getSymbols(ticker, auto.assign=FALSE, 
                                 from = sDate, to = eDate, warning = FALSE)),    
           error = function(e) {
             message("-ERROR-")
             message(paste("Error for ticker symbol  :", ticker, "\n"))
             message("Here's the original error message: ")
             message(e)
             message("")
             return(NULL)},
           finally = {
             message(paste("Data was processed for symbol:", "[", ticker, "]" ))
             message("\n","******************************************", "\n")  
           }) 
}
result <- do.call(cbind,lapply(ticker_symbol,get.symbol))
names(result) <- gsub("\\..+","",names(result))  # remove ".Adjusted" from names
head(result)
#              IVW   JKE   QQQ  SPYG   VUG
# 2007-09-04 61.71 65.37 46.56 52.42 57.36
# 2007-09-05 61.37 64.78 46.10 51.95 56.85
# 2007-09-06 61.47 65.13 46.06 52.18 57.13
# 2007-09-07 60.58 64.06 45.21 51.29 56.31
# 2007-09-10 60.36 64.13 45.18 51.24 56.12
# 2007-09-11 61.19 65.03 45.86 51.90 56.89

This takes advantage of the auto.assign=... argument of getSymbols(...) to avoid all this environment-setting and accumulation the temporary results in a list.



来源:https://stackoverflow.com/questions/27489387/r-code-to-rename-header-of-an-xts-object-using-nameobject-vector

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