Home > Software design >  Putting a value in a sublist
Putting a value in a sublist

Time:11-05

I have data as follows:

alist <- list()
vec <- c(1, 2, 3)

I want to put a value (in this case an object), into a sublist. But when I do:

for (i in 1:length(vec)) {
  alist[[i]][1] <- vec
}

this is for some reason not allowed: Error in *tmp* [[i]] : subscript out of bounds. Do I have to intialise every sublist? If so, what is the syntax for doing that?

Desired outcome:

desired_out <- list( list(alist = c(1, 2, 3) ), list(alist = c(1, 2, 3) ), list(alist = c(1, 2, 3) ))

EDIT:

An attempt to create a reproducible example for the entire loop (my actual data is a loop within a loop):

alist <- list()
vec <- c(1, 2, 3)

for (j in 1:2) {
  for (i in 1:length(vec)) {
  alist[[i]][j] <- vec
  }
}

CodePudding user response:

This does what you ask for, but I think your example is still to minimal for your original nested loop problem:

alist <- list()
vec <- c(1, 2, 3)

for (i in 1:length(vec)) {
  alist[[i]] <- list(alist = vec)
}

desired_out <- list(
                  list(alist = c(1, 2, 3)),
                  list(alist = c(1, 2, 3)),
                  list(alist = c(1, 2, 3))
                  )

identical(alist, desired_out)
#> [1] TRUE

Created on 2021-11-05 by the reprex package (v2.0.1)

CodePudding user response:

Create an empty list with length then fill it in:

x <- vector(mode = "list", length = 3)

for (j in 1:2) {
  for (i in 1:length(vec)) {
    # notice double square brackets
    x[[ i ]][[ j ]] <- vec
  }
}
  • Related