简体   繁体   English

如何在 R 中的多个数据框中转换列表?

[英]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) 执行相同操作?

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在 OP 的代码中,我们需要[[而不是[因为通过执行[ ,它仍然是长度为 1 的list

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.如果我们在全局环境中需要多个对象(不推荐), assignlist2env应该可以工作。 After naming the list with custom names or letters (a, b, c, ,..), use list2env使用自定义名称或letters (a、b、c、...)命名list后,使用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..注意:我们假设list_of_matrices的长度小于 26,否则必须将名称从内置letters更改为其他名称。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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