Reputation: 45
I am trying to add two vectors.
I tried just simply doing this
c <- a + b
The answer came out as 69, 10, 44, 6
. I am guessing it reused a?
I want c to be 69, 10, 3, 1
after adding a and b together.
I have no experience with R at all so please keep the solution simple. Thanks in advance!
Upvotes: 2
Views: 818
Reputation: 2129
When you add two vectors of different sizes, R recycles the one of shorter length. See: https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Recycling-rules. One solution is to pad out the shorter one with zeros as in tmfmnk's answer.
Upvotes: 0
Reputation: 39858
Another possibility could be:
c(a, rep(0, length(b) - length(a))) + b
[1] 69 10 3 1
Upvotes: 3
Reputation: 887118
It is due to recycling. We can prevent it by keeping the lengths same, but adding 0's
a1 <- `length<-`(a, length(b))
replace(a1, is.na(a1), 0) + b
#[1] 69 10 3 1
Or if there are multiple vectors, place it in a list
, set the length programmatically and use rowSums
which also have the na.rm
parameter
lst1 <- list(a, b)
rowSums(sapply(lst1, `length<-`, max(lengths(lst1))), na.rm = TRUE)
#[1] 69 10 3 1
Upvotes: 3