Sum all pairwise combinations of a vector in R

Viewed 53

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
3 Answers

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,`+`)

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

sapply can do but maybe not as efficient as outer

> sapply(vec,`+`,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
Related