将列表附加到 R 中的列表列表 [英] Appending a list to a list of lists in R

查看:33
本文介绍了将列表附加到 R 中的列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将数据附加到已采用列表格式的列表时遇到问题.我有一个程序可以在模拟循环期间导出结果对象.数据本身存储为矩阵列表.我的想法是将这些列表存储在一个列表中,然后将此列表列表保存为 R 对象以供以后分析,但是我在正确实现这一点时遇到了一些问题.我将展示我使用小抽象示例所做的工作,仅使用值而不是模拟中的矩阵数据:

I'm having issues appending data to a list which is already in a list format. I have a program which will export results objects during a simulation loop. The data itself is stored as a list of matrices. My idea is to store those lists in a list, and then save this list of lists as an R object for later analysis, however I'm having some issues achieving this correctly. I'll show what I've done with small abstract example just using values instead of the matrix data from my simulation:

假设我已经运行了 3 次模拟循环.在迭代过程中,需要将结果列表收集到我将保存为 R 对象的一个​​列表列表中:

Say I've run the simulation loop for 3 times. During the iterations, the results lists need to be collected into the one list of lists that I will save as an R object:

包含其他列表并保存的列表:outlist1 <- list()

List to contain the other lists and be saved: outlist1 <- list()

第一次迭代:resultsa <- list(1,2,3,4,5)

outlist <- append(outlist1,resultsa)

第二次迭代:resultsb <- list(6,7,8,9,10)

outlist <- append(outlist1,b)

第三次迭代:resultsc <- list(11,12,13,14,15)

outlist <- list(outlist2,c)

但是,此解决方案不适用于以这种方式增长包含列表的列表,所需的结果是:

However, this solution does not work with growing a list containing lists this way, the desired result is:

>outlist
[[1]]
[[1]][[1]]
[1] 1

[[1]][[2]]
[1] 2

[[1]][[3]]
[1] 3

[[1]][[4]]
[1] 4

[[1]][[5]]
[1] 5


[[2]]
[[2]][[1]]
[1] 6

[[2]][[2]]
[1] 7

[[2]][[3]]
[1] 8

[[2]][[4]]
[1] 9

[[2]][[5]]
[1] 10


[[3]]
[[3]][[1]]
[1] 11

[[3]][[2]]
[1] 12

[[3]][[3]]
[1] 13

[[3]][[4]]
[1] 14

[[3]][[5]]
[1] 15

然而,我得到的是:

> outlist3
[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
[1] 1

[[1]][[1]][[2]]
[1] 2

[[1]][[1]][[3]]
[1] 3

[[1]][[1]][[4]]
[1] 4

[[1]][[1]][[5]]
[1] 5


[[1]][[2]]
[[1]][[2]][[1]]
[1] 6

[[1]][[2]][[2]]
[1] 7

[[1]][[2]][[3]]
[1] 8

[[1]][[2]][[4]]
[1] 9

[[1]][[2]][[5]]
[1] 10

如何增加列表,使格式化的结果列表与所需的结果相似?如果我对这些列表进行进一步分析,我需要能够轻松访问这些元素.

How do I grow a list, such that the resulting list formatted is like the desired result? If I do further analysis on these list I need to be able to easily access the elements.

推荐答案

会不会是这个,你想要的:

Could it be this, what you want to have:

# Initial list:
myList <- list()

# Now the new experiments
for(i in 1:3){
  myList[[length(myList)+1]] <- list(sample(1:3))
}

myList

这篇关于将列表附加到 R 中的列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆