复制列表以创建列表列表 [英] Replicate a list to create a list-of-lists

查看:73
本文介绍了复制列表以创建列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建具有以下(嵌套)结构的列表:

I am trying to create a list with the following (nested) structure:

l <- list()
for(i in seq(5)) l[[i]] <- list(a=NA,b=NA)
> str(l)
List of 5
 $ :List of 2
  ..$ a: logi NA
  ..$ b: logi NA
 $ :List of 2
  ..$ a: logi NA
  ..$ b: logi NA
 $ :List of 2
  ..$ a: logi NA
  ..$ b: logi NA
 $ :List of 2
  ..$ a: logi NA
  ..$ b: logi NA
 $ :List of 2
  ..$ a: logi NA
  ..$ b: logi NA

我想通过rep或类似方法来执行此操作,因为我正在创建一堆空白列表,稍后我将对其进行填充.(我知道我可以通过引用来扩展列表它的下一个索引,但是在对两个深度进行索引时不起作用.

I'd like to do this via rep or similar, as I'm creating a whole bunch of blank lists which I will later fill in. (I'm aware that I can just expand a list via referring to its next index, but that doesn't work when indexing two-deep).

我认为rep为此起作用,但似乎没有. ?rep给出以下示例:

I thought that rep worked for this, but it does not appear to. ?rep gives the following example:

fred <- list(happy = 1:10, name = "squash")
rep(fred, 5)

哪个返回:

> str(rep(fred, 5))
List of 10
 $ happy: int [1:10] 1 2 3 4 5 6 7 8 9 10
 $ name : chr "squash"
 $ happy: int [1:10] 1 2 3 4 5 6 7 8 9 10
 $ name : chr "squash"
 $ happy: int [1:10] 1 2 3 4 5 6 7 8 9 10
 $ name : chr "squash"
 $ happy: int [1:10] 1 2 3 4 5 6 7 8 9 10
 $ name : chr "squash"
 $ happy: int [1:10] 1 2 3 4 5 6 7 8 9 10
 $ name : chr "squash"

换句话说,它使列表变平.

In other words, it flattens the list.

我也尝试过list( rep(fred,5) ),同样失败.

I've also tried list( rep(fred,5) ) which similarly fails.

如何复制列表列表?

推荐答案

我认为这与rep行为有关,您希望在rep之前先嵌套:

I think this has to do with rep behavior, you want to nest before you rep:

rep(list(fred),5)

str输出:

List of 5
 $ :List of 2
  ..$ happy: int [1:10] 1 2 3 4 5 6 7 8 9 10
  ..$ name : chr "squash"
 $ :List of 2
  ..$ happy: int [1:10] 1 2 3 4 5 6 7 8 9 10
  ..$ name : chr "squash"
 $ :List of 2
  ..$ happy: int [1:10] 1 2 3 4 5 6 7 8 9 10
  ..$ name : chr "squash"
 $ :List of 2
  ..$ happy: int [1:10] 1 2 3 4 5 6 7 8 9 10
  ..$ name : chr "squash"
 $ :List of 2
  ..$ happy: int [1:10] 1 2 3 4 5 6 7 8 9 10
  ..$ name : chr "squash"

这篇关于复制列表以创建列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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