How to add two different-sized vectors in R
Let's say there are vectors:
a <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
b <- c(1, 2, 3, 4)
How to add all the elements of a with the elements of b cyclically, so that the output is this result:
2, 4, 6, 8, 6, 8, 10, 12, 10, 12
If you can use slices, then it would be great
0
3 answers
To add two vectors (of any length), use the operator +
:
> rep(1, 8) + 1:4
[1] 2 3 4 5 2 3 4 5
In the case when the length of the larger vector is not a multiple of the length of the smaller one, in addition to the result, we get a warning:
> rep(1, 10) + 1:4
[1] 2 3 4 5 2 3 4 5 2 3
Warning message:
In rep(1, 10) + 1:4 :
longer object length is not a multiple of shorter object length
If desired, the warning output can be suppressed, for example, by using the suppressWarnings()
:
> suppressWarnings(rep(1, 10) + 1:4)
[1] 2 3 4 5 2 3 4 5 2 3
1
Author: aleksandr barakin, 2020-10-31 11:00:53
I would do this:
a <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
b <- c(1, 2, 3, 4)
a+rep(b, ceiling(length(a)/length(b)))[1:length(a)]
[1] 2 4 6 8 6 8 10 12 10 12
1
Author: aGricolaMZ, 2020-10-30 18:07:18
To add up, use plus a+b
a <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
b <- c(1, 2, 3, 4)
print(a+b)
0
Author: haker, 2020-10-31 14:30:07