繁体   English   中英

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

[英]How can I transform a list in multiple dataframes in R?

我有多个矩阵的列表。 我可以使用以下代码将此列表的一个项目转换为数据框:

as.data.frame(list_of_matrices[i])

但是,我如何以自动方式对所有索引 (i) 执行相同操作?

我试过:

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

但它没有用:

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

在 OP 的代码中,我们需要[[而不是[因为通过执行[ ,它仍然是长度为 1 的list

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

如果我们在全局环境中需要多个对象(不推荐), assignlist2env应该可以工作。 使用自定义名称或letters (a、b、c、...)命名list后,使用list2env

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

现在,我们检查

head(a)
head(b)

另一个选项是在循环本身中赋值

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

head(a)
head(b)

注意:我们假设list_of_matrices的长度小于 26,否则必须将名称从内置letters更改为其他名称。

尝试这个:

# 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