Adding multiple vectors in R
10,605
Solution 1
Here is another way, dropping NAs when sum the vectors:
df <- data.frame(vector1, vector2, vector3, vector4)
rowSums(df, na.rm=T)
Solution 2
Actually it's not as easy as it may seem. I reckon you want to get rid of NA's and replace them with 0 (zeros). Yet another solution is:
# create dummy variables
set.seed(1234)
x <- round(rnorm(10, 15, 3.2))
y <- round(runif(10, 12, 27))
z <- round(rpois(n = 10, lambda = 5))
# create some NA's
x[c(2,3)] <- NA
y[c(1,3,7)] <- NA
z[c(3,6,10)] <- NA
And now, if you do:
x + y + z # the result is:
[1] NA NA NA 20 31 41 NA 39 37 25
So run:
x[is.na(x)] <- 0
y[is.na(y)] <- 0
z[is.na(z)] <- 0
hence:
x + y + z # yields:
[1] 16 21 0 25 34 41 16 42 48 25
But, frankly, I recommend that you stick with @xiechao's solution! It's quite easy and straightforward!
Solution 3
here is where mapply comes to its field:
mapply(sum,Vector1,Vector2,Vector3,VectorN,na.rm = TRUE)
simple intelligent and clear
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on June 11, 2022Comments
-
Admin about 2 years
I have a problem where I have to add thirty-three integer vectors of equal length from a dataset in R. I know the simple solution would be
Vector1 + Vector2 + Vector3 +VectorN
But I am sure there is a way to code this. Also some vectors have NA in place of integers so I need a way to skip those. I know this may be very basic but I am new to this.
-
aL3xa over 14 yearsThis can also do the job:
apply(df, 1, sum, na.rm=TRUE)
-
petrelharp about 12 yearsthis only works if the list has two elements; otherwise it complains: "operator needs one or two arguments"
-
cloudscomputes over 5 yearsthis can't handle the NA case