英文:
How to sum up in two vector without overriding the results
问题
我想要将两个向量求和,方式如下:
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将是一个包含以下所有结果的向量:
for (i in B) {
for (j in A)
print(j + i)
}
我对矩阵不感兴趣。我可能该怎么做呢?谢谢。
英文:
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
答案1
得分: 1
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
英文:
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
<hr>
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论