Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

r - Replicate a list to create a list-of-lists

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

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).

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)

Which returns:

> 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.

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

How do I replicate a list-of-lists?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

rep(list(fred),5)

The str output:

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...