Loop through a vector of vectors

20,455

Solution 1

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.

Solution 2

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

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

Share:
20,455
Admin
Author by

Admin

Updated on November 16, 2020

Comments

  • Admin
    Admin over 3 years

    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)?