Home > database >  Sum all pairwise combinations of a vector in R
Sum all pairwise combinations of a vector in R

Time:06-08

I have a vector comprised of a set of numbers, for example:

vec <- c(1, 2, 3, 4, 5)

I wish to produce a matrix that contains the sum of each pairwise element within that vector - in this case:

     [,1] [,2] [,3] [,4] [,5]
[1,]   2    3    4    5    6
[2,]   3    4    5    6    7
[3,]   4    5    6    7    8
[4,]   5    6    7    8    9
[5,]   6    7    8    9    10

Thank you.

CodePudding user response:

You can use outer()

outer(vec,vec," ")

Output:

     [,1] [,2] [,3] [,4] [,5]
[1,]    2    3    4    5    6
[2,]    3    4    5    6    7
[3,]    4    5    6    7    8
[4,]    5    6    7    8    9
[5,]    6    7    8    9   10

Note: this may also be written as:

outer(vec,vec,` `)

CodePudding user response:

Here's one way.

vec <- c(1, 2, 3, 4, 5)

matrix(rowSums(expand.grid(vec, vec)), ncol = length(vec))

#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]    2    3    4    5    6
#> [2,]    3    4    5    6    7
#> [3,]    4    5    6    7    8
#> [4,]    5    6    7    8    9
#> [5,]    6    7    8    9   10
  •  Tags:  
  • r
  • Related