Daniel Daniel - 1 year ago 106
R Question

Compute Row Differences

I have a matrix such as:

m <- matrix(data=cbind(rnorm(30, 0), rnorm(30, 2), rnorm(30, 5)), nrow=30, ncol=3)

What I want:
Matrix with differences between every row (for all columns).
The result (snapshot) might look like this:

enter image description here

Answer Source

If it is between each combination of rows,

t(combn(nrow(m), 2, FUN = function(i) m[i[1],]- m[i[2],]))

Or using expand.grid to also include the difference of the same rows.

 d1 <- expand.grid(1:nrow(m), 1:nrow(m))
 rn <- do.call(paste, c(d1,  sep=";"))
 res <- t(apply(d1, 1, function(i) m[i[1],] - m[i[2],]))
 row.names(res) <- rn
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download