Adding a Special Vector to R

I would like to add 2 vectors as follows , but avoid for loops. Is there a simple method?

vadd<-function(vrow,vcol){
vmatrix<-matrix(nrow=length(vrow),ncol=length(vcol))
for(r in 1:length(vrow)){#rows
    for(c in 1:length(vcol)){#columns
        vmatrix[r,c]<-vrow[r]+vcol[c]
    }
}
return(vmatrix)
}

a<-c(1:10)
b<-c(3:4)
vadd(a,b)

Regards, Brian

+3
source share
3 answers

What you are looking for is outer()as in:

> outer(a, b, "+")
      [,1] [,2]
 [1,]    4    5
 [2,]    5    6
 [3,]    6    7
 [4,]    7    8
 [5,]    8    9
 [6,]    9   10
 [7,]   10   11
 [8,]   11   12
 [9,]   12   13
[10,]   13   14
+11
source

You can put binto the matrix and use the rules for recycling R:

a + matrix(b, nrow=length(a), ncol=2, byrow=TRUE)
+3
source

Here is what you can do:

a<-c(1:10)
b<-c(3:4)

matrix(b,length(a),2,byrow=TRUE)+a
+3
source

All Articles