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
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