Search code examples
rdataframequantmod

Remove row names from a list of dataframes?


My code:

library(quantmod)
library(tseries)
library(ggplot2)
companies = c("IOC.BO", "BPCL.BO", "ONGC.BO", "HINDPETRO.BO", "GAIL.BO")
stocks = list()
for(i in 1:5){
 stocks[[i]] = getSymbols(companies[i], auto.assign = FALSE)
}

stocks is a list of dataframes. Now I'm trying to bind the all $adjusted columns all the dataframes stored in stock but to do that I need to remove the rownames (someone please tell me if there's a better method to do this):

for(i in 1:5)
 rownames(stocks[[i]])<- NULL

but the resulting dataframes still have their row names, could someone please tell me where I'm going wrong?

P.S. Further my end goal is to have a dataframe with only the adjusted columns of the dataframes in the list stocks for which I did this:

adjusted=data.frame()
for(i in 1:5)
  coln=stocks[[1]][,6]
  adjusted=cbind(ajusted,coln)
adjusted

but this returns adjusted as a list.


Solution

  • Row names

    Regarding row names after running the code in the question

    rownames(stocks[[1]])
    ## NULL
    

    so it is not true that stocks have row names afterwards.

    Adjusted series

    To create a time series of adjusted values use Ad as shown below.

    Adjusted <- do.call("merge", lapply(stocks, Ad))
    

    Putting it all together

    Note that we don't really need the entire row names processing and the following is sufficient. The second last line is optional as its only purpose is to make the column names nicer and the last line converts the xts object Adjusted to a data frame and may not be needed either since you may find working with an xts object more convenient than using data frames.

    library(quantmod)
    library(ggplot2)
    
    stocks <- lapply(companies, getSymbols, auto.assign = FALSE)
    Adjusted <- do.call("merge", lapply(stocks, Ad))
    names(Adjusted) <- sub(".BO.Adjusted", "", names(Adjusted))
    adjustedDF <- fortify(Adjusted)