Vector to Matrix of Differences between elements

matrix, r, vector

Solution

This is typically done with `outer`.

outer(1:5, 1:5, '-')

See `?outer` for details.

Problem

Given a vector: ``` vec <-1:5 ``` What is an efficient way to create a matrix where the difference between the vector components are displayed in a matrix, a difference matrix, if you will. I could obviously do this with two for loops, but I need to do this with a much larger set of data. There is likely a term for this matrix I am trying to make, but I am not having any luck finding it. Here is what the result would look like. ``` m<-matrix(c(NA), ncol=5, nrow=5, byrow=TRUE) rownames(m)<-1:5;colnames(m)<-1:5 for(i in 1:5){for(j in 1:5){m[i,j]<-(as.numeric(rownames(m)[i])-as.numeric(rownames(m)[j]))}} m ``` Thanks for any help!

Original source