Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sum up in two vector without overriding the results

I would like to sum up two vectors, in a way that:

A = seq(10, 30, 10)
B = seq(1, 6, 1)
C = c()

for (i in B) {
  for (j in A)
  C = c(j + i)
}

C would be a vector with all results appearing from:

for (i in B) {
  for (j in A)
  print(j + i)
}

I am not interested in a matrix for this. What could I possibly do?
Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use outer in this case.

c(outer(A, B, `+`))
[1] 11 21 31 12 22 32 13 23 33 14 24 34 15 25 35 16 26 36

If you really need a for loop, we can use the approach provided by @Feel free in the comment:

for (i in B) {
  for (j in A)
    C = append(C, j + i)
}

C
[1] 11 21 31 12 22 32 13 23 33 14 24 34 15 25 35 16 26 36
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading