wussyx
wussyx

Reputation: 85

For Loop in R not printing what I need

In R, I would like elements in list1 to be added to list2

list1 = c(1,2,3,4)
list2 = c(2,4,6,8)

for(i in list1){
  for(j in list2){
    print(i + j)
  }
}

I am looking for the loop to return

3
6
9
12

but it returns

3
5
7
4
6
8
5
7
9

how can I get it to return the first former case?

Upvotes: 2

Views: 111

Answers (3)

Arun kumar mahesh
Arun kumar mahesh

Reputation: 2359

if you are using for loop we need to mention jth interation equals to i.

for(i in list1){
  for(j in list2[list1==i]){
    print(i + j)
  }
}
[1] 3
[1] 6
[1] 9
[1] 12

Upvotes: 1

igorkf
igorkf

Reputation: 3565

library(tidyverse)

list1 = c(1,2,3,4)
list2 = c(2,4,6,8)

purrr::walk2(list1, list2, ~print(.x + .y))
[1] 3
[1] 6
[1] 9
[1] 12

list1 is the .x and list2 is the .y

Upvotes: 1

Oliver
Oliver

Reputation: 8572

This is a classic question and duplicate of many other questions.

Each for loop iterates over the iterator. The comments answer you question but for understanding below is an example that will show you 'why' this is happening:

list1 = c(1,2,3,4)
list2 = c(2,4,6,8)
for(i in seq_along(list1)){
  for(j in seq_along(list2)){
    cat("list1[[", i,"]] + list2[[", j,"]] =",list1[[i]],"+",list2[[j]],"=", list1[[i]] + list2[[j]],"\n")
  }
}

This should illustrate how the for loop works.

Upvotes: 1

Related Questions