Suppose we would like to store pairs as elements in a list, e.g.,
> x <- list()
> x[[1]] <- list(1,2)
> x[[2]] <- list(3,4)
> x
[[1]]
[[1]][[1]]
[1] 1
[[1]][[2]]
[1] 2
[[2]]
[[2]][[1]]
[1] 3
[[2]][[2]]
[1] 4
If one wants to create the same thing with concatenation, without explicit reference to an index of the outer list, a natural approach (see EDIT below for motivation for this approach) is
> c(list(list(1,2)),list(3,4))
[[1]]
[[1]][[1]]
[1] 1
[[1]][[2]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
Is there a way to avoid the "flattening" of the second argument to c()
and thereby use concatenation to produce x
?
EDIT: I should have made my intended application clear.
In the end, I would like to add pairs to a list whenever I find one as I go through a loop. Currently I maintain an index for the main list to add new pairs to the end of it when one is found, however using c
is perhaps more natural. So using an explicit index the loop may look like this
index <- 1
l <- list()
for (i in 1:10) {
for (j in (i+1):10) {
if ( (i+j)%%2 == 0 ) {
l[[index]] <- list(i,j)
index <- index + 1
}
}
}
And the failed attempt to use c
looks like this
l <- list()
for (i in 1:10) {
for (j in (i+1):10) {
if ( (i+j)%%2 == 0 )
l <- c(l,list(i,j))
}
}
ANSWER: as noted by Tommy below, an extra list() is needed, so the following works:
l <- list()
for (i in 1:10) {
for (j in (i+1):10) {
if ( (i+j)%%2 == 0 )
l <- c(l,list(list(i,j)))
}
}
Kind of obvious thing I should have figured out. Tommy also notes that this might not be a very good way of doing things.