Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add two vectors WITHOUT repeating in R?

Tags:

r

vector

I have two vectors in R of different size, and I want to add them, but without repeating the shorter one - instead, I want the "missing" numbers to be zeroes.

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.

like image 669
Karel Bílek Avatar asked Feb 21 '10 20:02

Karel Bílek


People also ask

How do you combine two vectors in R?

To concatenate two or more vectors in r we can use the combination function in R. Let's assume we have 3 vectors vec1, vec2, vec3 the concatenation of these vectors can be done as c(vec1, vec2, vec3). Also, we can concatenate different types of vectors at the same time using the same function.

How to remove duplicates in vector in R?

To remove the duplicate rows or elements from vector or data frame, use the base functions like unique() or duplicated() method. If you deal with big data set and remove the duplicate rows, use the dplyr package's distinct() function.

Can we add two vectors in R?

We can add two vectors together using the + operator. One thing to keep in mind while adding (or other arithmetic operations) two vectors together is the recycling rule. If the two vectors are of equal length then there is no issue.

How do I sum multiple vectors in R?

The sum() is a built-in R function that calculates the sum of a numeric input vector. It accepts a numeric vector as an argument and returns the sum of the vector elements. To calculate the sum of vectors in R, use the sum() function.


1 Answers

I would make them equal length then add them:

> 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're just adding two vectors, it may be more intuitive to work with it like this:

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

Here's another solution using rep:

x <- c(x, rep(0, length(y)-length(x)))
x + y
like image 120
Shane Avatar answered Oct 28 '22 02:10

Shane