Add each element in one vector with each element in a second vector

后端 未结 3 981
攒了一身酷
攒了一身酷 2021-01-20 01:48

I would like to add each element in one vector with each element in another vector as follows, but avoid the for loops. Is there a simple method?



        
相关标签:
3条回答
  • 2021-01-20 02:01

    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
    
    0 讨论(0)
  • 2021-01-20 02:04

    You can put b in a matrix and take advantage of R's recycling rules:

    a + matrix(b, nrow=length(a), ncol=2, byrow=TRUE)
    
    0 讨论(0)
  • 2021-01-20 02:17

    Here is one thing you can do:

    a<-c(1:10)
    b<-c(3:4)
    
    matrix(b,length(a),2,byrow=TRUE)+a
    
    0 讨论(0)
提交回复
热议问题