Ari*_*man 9 r list nested-lists
我正在尝试使用以下(嵌套)结构创建一个列表:
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
Run Code Online (Sandbox Code Playgroud)
我想通过rep或类似的方式做到这一点,因为我正在创建一大堆空白列表,我将在后面填写.(我知道我可以通过引用其下一个索引来扩展列表,但是索引两深时不起作用).
我认为这对此rep有用,但似乎没有. ?rep给出以下示例:
fred <- list(happy = 1:10, name = "squash")
rep(fred, 5)
Run Code Online (Sandbox Code Playgroud)
哪个回报:
> 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"
Run Code Online (Sandbox Code Playgroud)
换句话说,它使列表变得平坦.
我也尝试list( rep(fred,5) )了类似的失败.
如何复制列表列表?
And*_*ndy 12
我认为这与代理行为有关,你想在代表之前嵌套:
rep(list(fred),5)
Run Code Online (Sandbox Code Playgroud)
的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"
Run Code Online (Sandbox Code Playgroud)
您可以使用replicate:
l <- replicate(5, list(a=NA,b=NA), simplify=FALSE)
Run Code Online (Sandbox Code Playgroud)