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
.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With