Search code examples
rxts

Gathering separate data into a single its object in R


I'm trying to use R to measure stock performance. The sample code is from here: https://towardsdatascience.com/how-to-measure-stock-portfolio-performance-using-r-847c992195c2

In the section of code below we're trying to gather separate data into a single xts object. However, the resulting xts object would only list data from one date, rather than the entire date range that was specified. Sample code below:

 # IDX-BUMN20 Create Dataframe
 Index <- list(AAPL, NLY, FVRR)
 names(Index) <- IDXBUMN20
 Index <- lapply(Index, '[', i = 1, j = 6) # select only Adjusted close price
 Index <- do.call(cbind.data.frame, Index) #List to Dataframe
 names(Index) <- IDXBUMN20 # change colnames

 Index <- as.xts(Index)

Thank you very much for your help, novice here.


Solution

  • Merge the data instead of cbind. Also i = 1 keeps only 1 row, the link that you shared keeps it empty meaning selecting all the rows.

    library(quantmod)
    IDXBUMN20 = c('AAPL','NLY','FVRR')
    getSymbols(IDXBUMN20)
    
    Index <- list(AAPL, NLY, FVRR)
    names(Index) <- IDXBUMN20
    Index <- lapply(Index, '[', i =,j = 6) 
    Index <- do.call(merge, Index) 
    names(Index) <- IDXBUMN20