Search code examples
rloopsvectordoublepairwise

Pairwise loop through multiple vectors in R


What do I have in R?

The following vectors:

N <- c('a','b')
M <- c('x','y')

The goal.

While keeping the vectors intact (I do not wish to combine them into a matrix), I would like to call the elements of the vectors in the following pairwise fashion:

"a" "x" "b" "y"

The code so far.

I've tried to use a for loop, but in the way it is written below, it is read as a nested for loop:

for (i in M) for (j in N)  { 
 print(i)
 print(j)
}

Which results in:

"a" "x" "a" "y" "b" "x" "b" "y"

What I've searched for.

Using search terms as multiple indices, for loops, and double loops, I was only able to find information on nested loops. The use of flow commands did not help me in my quest.

The real goal.

I would like to add one line of text into an image. The textual tags are stored in a single vector and the images are as well. The code I have so far works, except for calling the elements of the vectors in the pairwise fashion explained above. There are plenty of pictures and life's too short to do it all by hand.

Any help would be greatly appreciated!

Stijn


Solution

  • The way it is explained in the "real goal", each element in the "textual tags" vectors corresponds to one in the "images vector". If that's correct, isn't the solution as simple as (given that both vectors have the same length):

    for (i in textTags)
      addThisToThat(textTags[i], images[i])