How to add two vectors without repeating in R?

I have two vectors in R of different sizes, and I want to add them, but without repeating the shorter one — instead, I want the “missing” numbers to be zeros.

Example:

x<-c(1,2) y<-c(3,4,5) z<-x+y 

Now z is 4 6 6 , but I want it only 4 6 5 .

+7
vector r
source share
1 answer

I would make them equal in length and then add:

 > length(x) <- length(y) > x [1] 1 2 NA > x + y [1] 4 6 NA > x[is.na(x)] <- 0 > x + y [1] 4 6 5 

Or, as a function:

 add.uneven <- function(x, y) { l <- max(length(x), length(y)) length(x) <- l length(y) <- l x[is.na(x)] <- 0 y[is.na(y)] <- 0 x + y } > add.uneven(x, y) [1] 4 6 5 

Given that you are just adding two vectors, it may be more intuitive to work with it as follows:

 > `%au%` <- add.uneven > x %au% y [1] 4 6 5 

Here is another solution using rep:

 x <- c(x, rep(0, length(y)-length(x))) x + y 
+12
source share

All Articles