简体   繁体   中英

R - sum each element in a vector with each element of other vector

I have two vectors and I want a new vector which elements are the sum of an element of vector 1 and an element of vector 2.

v1<-c(1,2,3,4,5,6)
v2<-c(0,1,1,2,2,1)

for(i in 1:length(v1)){
  for(j in 1:length(v2)){
    n<-vector()
    n<-v1[i]+v2[j]
  }
  m<-NULL
  m[n]<-m
}

When I run the loop, I get m=NULL and n is numeric class with NA . Any idea?

Perhaps we need

tapply(c(v1, v2), c(v1, v2), FUN = sum)

Or just

v1 + v2

Or could be outer

outer(v1, v2, FUN = "+")

If you want to correct your code, you can try something like this:

v1<-c(1,2,3,4,5,6)
v2<-c(0,1,1,2,2,1)

m<-matrix(rep(0,length(v1)*length(v2)), nrow=length(v1))
for(i in 1:length(v1)){
  for(j in 1:length(v2)){
    m[i,j] <- v1[i]+v2[j]
  }
}
m
      [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    2    2    3    3    2
[2,]    2    3    3    4    4    3
[3,]    3    4    4    5    5    4
[4,]    4    5    5    6    6    5
[5,]    5    6    6    7    7    6
[6,]    6    7    7    8    8    7

This can also be done this way

outer(v1, v2, FUN='+')

or in this way

matrix(apply(expand.grid(1:length(v1), 1:length(v2))[2:1], 1, 
                         function(x)v1[x[1]]+v2[x[2]]), nrow=length(v1), byrow=TRUE)
      [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    2    2    3    3    2
[2,]    2    3    3    4    4    3
[3,]    3    4    4    5    5    4
[4,]    4    5    5    6    6    5
[5,]    5    6    6    7    7    6
[6,]    6    7    7    8    8    7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM