List of vectors

i'm trying to create list of vectors vector(mode = "list",length = 5) ,as you know when we create this kind of vectors each vector contain by default one vector so i can easily access that vector and add values to it ,for example : v[[1[1]]]<-append(v[[1[1]]],c(1,2,3)) , the problem that i need to access the second vector or third vector in vector 1 , when i'm trying to do it i got this error message
Error in v[[1[2]]] <- 1 :
attempt to select more than one element in integerOneIndex
any ideas or suggestions

Hi @ahmad_anaqreh! So you're trying to create a list of vectors using:

v = vector(mode = "list", length = 5)
# [[1]]
# [[2]]
# [[3]]
# [[4]]
# [[5]] NULL

This is, so far, an empty list (as far as I know, using the vector function in this way is the same as using list(NULL, NULL, NULL, NULL, NULL)).

I'm not entirely sure what you're asking, but when you say that you want to access 'the second or third vector in vector 1', it sounds like you want to nest vectors more than once. Is that what you want?

If that is the case, I'd say you want a list on the second level, not a vector, as vectors are atomic—that is, they can't contain other vectors or lists.

So maybe v[[3]] = list('apple', c(19, 26), 'banana'). Then:

  • v[[3]][[1]] is 'apple'
  • v[[3]][[2]] is the vector c(19, 26)
  • v[[3]][[2]][2] is the 26.

Notice that when we have the indices for the list and vector elements, they're next to each other, not nested inside each other. That could explain the error you're seeing.

Also note that, in the third bullet point, the list elements are accessed using [[ n ]], while the vector element is accessed using [ n ].

I hope that helps!


hello @rensa it's working perfectly ,thank you so much :slight_smile:

1 Like