Elais
Elais

Reputation: 43

Adding multiple vectors in R

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.

Upvotes: 4

Views: 11711

Answers (5)

Soren Havelund Welling
Soren Havelund Welling

Reputation: 1893

add = function(...) {
  vectors = list(...)
  res=vectors[[1]]
  for(i in vectors[-1]) res = res + i
  return(res)
}

add(1:3,4:5,1:3)

Upvotes: 0

cloudscomputes
cloudscomputes

Reputation: 1484

here is where mapply comes to its field:

mapply(sum,Vector1,Vector2,Vector3,VectorN,na.rm = TRUE)

simple intelligent and clear

Upvotes: 2

Jonathan Chang
Jonathan Chang

Reputation: 25337

do.call("+", list(vector1, vector2, vector3, vector4))

Upvotes: 0

aL3xa
aL3xa

Reputation: 36080

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!

Upvotes: 1

xiechao
xiechao

Reputation: 2361

Here is another way, dropping NAs when sum the vectors:

df <- data.frame(vector1, vector2, vector3, vector4)
rowSums(df, na.rm=T)

Upvotes: 8

Related Questions