Looping over multiple lists with base R

Viewed 11661

In python we can do this..

numbers = [1, 2, 3]
characters = ['foo', 'bar', 'baz']

for item in zip(numbers, characters):
    print(item[0], item[1])

(1, 'foo')
(2, 'bar')
(3, 'baz')

We can also unpack the tuple rather than using the index.

for num, char in zip(numbers, characters):
    print(num, char)

(1, 'foo')
(2, 'bar')
(3, 'baz')

How can we do the same using base R?

7 Answers

The tidyverse solution would be to use purrr::map2 function. Ex:

numbers <- c(1, 2, 3)
characters <- c('foo', 'bar', 'baz')

map2(numbers, characters, ~paste0(.x, ',', .y))

#[[1]]
#[1] "1,foo"

#[[2]]
#[1] "2,bar"

#[[3]]
#[1] "3,baz"

See API here

Other scalable alternatives: Store the vectors in the list and iterate over.

vect1 <- c(1, 2, 3)
vect1 <- c('foo', 'bar', 'baz')
vect2 <- c('a', 'b', 'c')


idx_list <- list(vect1, vect2)
idx_vect <- c(1:length(idx_list[[1]]))

for(i in idx_vect){
    x <- idx_list[[1]][i]
    j <- idx_list[[2]][i]
    print(c(i, x, j))
}
Related