user1320502
user1320502

Reputation: 2570

replicate within list element to make nested list

say we have

a <- list(letters[1:4],letters[5:6])

how can we duplicate within each element to get a list like

b <- list(list(letters[1:4],letters[1:4]),list(letters[5:6],letters[5:6]))

I could make an empty list, for a[1] and a[2] fill it with replicated vectors then add it all in one big list.

but i think there should be a quick way that I am missing?

i did

lapply(a, function(x){replicate(2,x, simplify=FALSE)})

but the indexing seems strange e.g.

[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
[1] "a" "b" "c" "d"

[[1]][[1]][[2]]
[1] "a" "b" "c" "d"

Upvotes: 2

Views: 104

Answers (2)

BrodieG
BrodieG

Reputation: 52637

You can apply replicate to each element in your list. Here we do so with lapply:

lapply(a, replicate, n=2, simplify=F)

n and simplify are arguments forwarded by lapply to replicate (see ?replicate). This produces:

List of 2
 $ :List of 2
  ..$ : chr [1:4] "a" "b" "c" "d"
  ..$ : chr [1:4] "a" "b" "c" "d"
 $ :List of 2
  ..$ : chr [1:2] "e" "f"
  ..$ : chr [1:2] "e" "f"

Note we're showing the output of str(...) for clarity, not the actual result.

Upvotes: 1

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162321

Here's one option:

lapply(a, function(X) rep(list(X), 2))
# [[1]]
# [[1]][[1]]
# [1] "a" "b" "c" "d"
# 
# [[1]][[2]]
# [1] "a" "b" "c" "d"
# 
# 
# [[2]]
# [[2]][[1]]
# [1] "e" "f"
# 
# [[2]][[2]]
# [1] "e" "f"

Upvotes: 2

Related Questions