Adding multiple vectors to R

I have a problem where I have to add thirty-three integer vectors of equal length from a dataset in R. I know that a simple solution would be

Vector1 + Vector2 + Vector3 +VectorN

But I'm sure there is a way to code this. Also, some vectors have NA instead of integers, so I need to skip them. I know this can be very simple, but I am new to this.

+3
source share
5 answers

Here's another way: reset NA when summing vectors:

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

In fact, it is not as simple as it might seem. I believe that you want to get rid of NA and replace them with 0 (zeros). Another solution:

# 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 this:

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

from here:

x + y + z  # yields:
[1] 16 21  0 25 34 41 16 42 48 25

, , @xiechao! !

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

mapply :

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

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

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

Source: https://habr.com/ru/post/1737194/


All Articles