Jujename
Jujename

Reputation: 27

for loop over two variables in parallel

I'm looking for doing a loop with two variables at the same time.

let's say I have this df

fruits
apple
apple_others
banana
banana_others
orange
orange_others

I want to create a subset for each fruits (with just 'apple' & 'apple_others'). Let's say I manually set up list_a =c('apple','banana','orange') and list_b = c('apple_others','banana_others','orange_others').

how can I do something like

for (i in list_a) & (j in list_b) {
    subset(df, fruits == i | fruits == j)
}

to get

subset = apple & apple_others
do what I want
-----
subset = banana&banana_others
do what I want

A nested loop is not what I'm looking for since it will create

subset = apple&apple_others
do what I want
------
subset = apple&banana_others
do what I want

Upvotes: 0

Views: 225

Answers (2)

Jujename
Jujename

Reputation: 27

Just for the record, very easy answer if lists have the same len :

for (i in range_list) { 
list_a[i] 
list_b[i] 
}

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388982

You can use Map :

list_a =c('apple','banana','orange')
list_b = c('apple_others','banana_others','orange_others')

Map(function(x, y) {do What I want}, list_a, list_b)

For example, if you want to paste the two variables together.

Map(function(x, y) paste(x, y), list_a, list_b)

#$apple
#[1] "apple apple_others"

#$banana
#[1] "banana banana_others"

#$orange
#[1] "orange orange_others"

To use it in for loop you can iterate over the index of one of the value.

for (i in seq_along(list_a)) {
  print(paste(list_a[i], list_b[i]))
  do What I want
}

Upvotes: 1

Related Questions