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