Search code examples
rdataframexts

How to convert mutiple dataframes in a list to xts object


I have a list that list consisting of 1000 data frames each data frame having first column as Date. I want to convert all these data frames into xts object.

I have converted date into Date object using lapply.

I want to convert every data frame to xts in one command not individually one by one as it will take much time.


Solution

  • An option is to loop over the list, remove the first column which is the 'Date', apply the xts and specify the order.by as the first column (assuming that the class of 'Date' column is Date)

    library(xts)
    lst2 <- lapply(lst1, function(x) xts(x[-1], order.by = x[,1]))
    

    data

    set.seed(24)
    lst1 <- list(data.frame(Date = seq(as.Date('2015-01-01'), 
      length.out = 10, by = '1 day'), Col2 = rnorm(10)),
         data.frame(Date = seq(as.Date('2017-01-01'), 
       length.out = 10, by = '1 day'), Col2 = rnorm(10)))