16
votes

When I loop through a vector of vectors, the result of each loop is several vectors. I would expect the result of each loop to be a vector. Please see the following example:

foo <- seq(from=1, to=5, by=1)
bar <- seq(from=6, to=10, by=1)
baz <- seq(from=11, to=15, by=1)
vects <- c(foo,bar,baz)
for(v in vects) {print(v)}

# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5
# [1] 6
# [1] 7
# [1] 8
# [1] 9
# [1] 10
# [1] 11
# [1] 12
# [1] 13
# [1] 14
# [1] 15

This is odd as I would expect three vectors given it (should) iterate three times given the vector, c(foo,bar,baz). Something like:

# [1]  1  2  3  4  5
# [1]  6  7  8  9 10
# [1] 11 12 13 14 15

Can anyone explain why I am getting this result (15 vectors) and how to achieve the result I am looking for (3 vectors)?

2
There's no such thing as a vector of vectors in R. The function c just concatenates the three vectors you give it into one long vector.user399470
@Seth, yes there is a vector of vectors. A list is the generic vector in R and it can contain vectors. We might call them lists but as far as R is concerned it is a vector. (As compared to an atomic vector which holds only one data type, a list is a vector the elements of which can hold any data type.)Gavin Simpson
I wonder why this was downvoted? What is wrong? The question is clear and reproducible, and contains expected output. I am at a loss to know why this Q was worthy of a downvote, especially one without a comment to say why?!Gavin Simpson

2 Answers

20
votes

Look at what vects is:

> vects
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15

The c() joins (in this case) the three vectors, concatenating them into a single vector. In the for() loop, v takes on each values in vects in turn and prints it, hence the result you see.

Did you want a list of the three separate vectors? If so

> vects2 <- list(foo, bar, baz)
> for(v in vects2) {print(v)}
[1] 1 2 3 4 5
[1]  6  7  8  9 10
[1] 11 12 13 14 15

In other words, form a list of the vectors, not a combination of the vectors.

3
votes

Substitute vects <- list(foo,bar,baz) for vects <- c(foo,bar,baz).

There is no such thing (really) as a vector of vectors.