1

I have a "Large list" of 831 elements and I'd like to turn each individual element into matrix form without disturbing the structure of the list. However I can only get the first element to be converted, any help would be greatly appreciated - I'm a noob when it comes to anything like this thanks!

list_to_matrix <- function(data) {


  for (i in 1:length(data)) {

  data[[i]] <- as.matrix(data[[i]]) 

  return(data[[i]])

  }

}
  • Does that help https://stackoverflow.com/questions/13224553/how-to-convert-a-huge-list-of-vector-to-a-matrix-more-efficiently – Andre Wildberg Dec 24 '20 at 03:45

1 Answers1

1

You can use lapply :

list_to_matrix <- function(data) {
  lapply(data, as.matrix)
}

data1 <- list_to_matrix(data)

As far as your approach is concerned it should work if you take out the return line within the for loop.

list_to_matrix <- function(data) {
  for (i in 1:length(data)) {
    data[[i]] <- as.matrix(data[[i]]) 
  }
  return(data)
}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213