Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding multiple vectors in R

Tags:

r

vector

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.

like image 994
Elais Avatar asked Jan 22 '23 10:01

Elais


2 Answers

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

df <- data.frame(vector1, vector2, vector3, vector4)
rowSums(df, na.rm=T)
like image 83
xiechao Avatar answered Jan 24 '23 23:01

xiechao


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!

like image 39
aL3xa Avatar answered Jan 24 '23 23:01

aL3xa