Search code examples
rlistdataframemultiple-columnsquantmod

Applying Colnames() function on several objects in one code


I have downloaded A LOT of equity data using the getSymbols function from Quantmod. I am now trying to change the column names for all of these to the following by using the code below:

StockColumnNames <- c("Open","High","Low","Close","Volume","Adjusted Close")
colnames() <- StockColumnNames

Now this works fine on just one stock, however, I have the data of about 800. I was wondering if there's anyway that I could do this in a small piece of code?

If I put the following in the code it gives me this error:

C20_stock_List <- c("NZYM-B.CO","DANSKE.CO","DSV.CO","CARL-B.CO","MAERSK-A.CO","WDH.CO","LUN.CO","TDC.CO","GN.CO","MAERSK-B.CO","NOVO-B.CO","COLO-B.CO","JYSK.CO","ISS.CO","VWS.CO","CHR.CO","GEN.CO","PNDORA.CO","NETS.CO")
getSymbols(C20_stock_List, from = '2017-01-01')
colnames(C20_stock_List) <- StockColumnNames

> colnames(C20_stock_List) <- StockColumnNames

Error in colnames<-(*tmp*``, value = c("Open", "High", "Low", "Close", : attempt to set 'colnames' on an object with less than two dimensions

Does anyone have a solution for this? Thanks a bunch in advance.


Solution

  • Here are two approaches:

    library(quantmod)
    C20_stock_List <- c("NZYM-B.CO","DANSKE.CO","DSV.CO")
    getSymbols(C20_stock_List, from = '2017-01-01')
    
    StockColumnNames <- c("Open","High","Low","Close","Volume","Adjusted Close")
    lapply(C20_stock_List, function(x, StockColumnNames_) {
      z <- get(x, envir = .GlobalEnv)
      colnames(z) <- StockColumnNames_
      assign(x, value = z, envir = .GlobalEnv)
      return()
    }, StockColumnNames_ = StockColumnNames)
    

    When getting multiple symbols, instead of having all the symbols appear in the .GlobalEnv, assign them into an environment. This approach might be easier for most tasks related to looping across the data in each symbol:

    e <- new.env()
    getSymbols(C20_stock_List, from = '2017-01-01', auto.assign = TRUE, env = e)
    
    for (sym in C20_stock_List) {
      colnames(e[[sym]]) <- StockColumnNames
    }
    
    head(e$DANSKE.CO)