简体   繁体   中英

Converting each element of a “Large list” to a matrix in R

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]])

  }

}

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM