简体   繁体   中英

How can I transform a list in multiple dataframes in R?

I have a list of multiple matrices. I can transform an item of this list into a dataframe using this code:

as.data.frame(list_of_matrices[i])

But how can I do the same in an automatic way for all indexes (i)?

I tried:

a <- data.frame()
for(i in 1:length(list_of_matrices)){
  dataframes[i] <- as.data.frame(list_of_matrices[i])
}

but it didn't work:

Error in `[[<-.data.frame`(`*tmp*`, i, value = list(X1 = 1:102, X2 = c(2L,  : 
  replacement has 102 rows, data has 0

In the OP's code, we need [[ instead of [ because by doing [ , it will still be a list of length 1

for(i in seq_along(list_of_matrices)){
    list_of_matrices[[i]] <- as.data.frame(list_of_matrices[[i]])
  }

If we need multiple objects in the global env, (not recommended), either assign or list2env should work. After naming the list with custom names or letters (a, b, c, ,..), use list2env

names(list_of_matrices) <- letters[seq_along(list_of_matrices)]
list2env(list_of_matrices, .GlobalEnv)

Now, we check for

head(a)
head(b)

Another option is `assign with in the loop itself

for(i in seq_along(list_of_matrices)) {
    assign(letters[i], as.data.frame(list_of_matrices[[i]])
 }

head(a)
head(b)

NOTE: We assume that the length of list_of_matrices is less than 26 or else have to change the names from the built-in letters to something else..

Try this:

# Example list of matrices
mat_list <- list(
  matrix(runif(20), 4, 5),
  matrix(runif(20), 4, 5)
)
# Convert to list of df
df_list <- lapply(mat_list, as.data.frame)

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