Jim Fredrickson
Jim Fredrickson

Reputation: 117

subtract every value in a vector from every other value in the vector R

Say I have a matrix

    data<-matrix(seq(1,6),ncol=2,nrow=3,byrow=TRUE)
          A  B
    [1,]  1  2
    [2,]  3  4
    [3,]  5  6

Starting with column 'A' I want to create a vector of the pairwise differences between every number in 'A' and every other number in 'A'. In effect:

    c(1-1, 1-3, 1-5, 3-1, 3-3, 3-5, 5-1, 5-3, 5-5)

Then I need to do the same thing with the second column and so on. Eventually I need to bind these vectors into a new matrix of differences.

I feel like this should be doable with the apply functions, or perhaps sweep(), but I just could not get it together.

Thank you for your help!

PS. If the answer involves writing a function or a for loop could you please give me a dummy-medium level explanation? I am learning coding for the first time and I still cannot get my head around for loops and I still struggle with the logic of writing my own functions.

Upvotes: 3

Views: 2746

Answers (1)

akrun
akrun

Reputation: 887148

If we need to do the subtraction on each pairwise elements on each column, then loop over the columns of matrix with apply, get the pairwise, combinations as a two column data.frame with expand.grid and subtract the columns using Reduce

apply(data, 2, FUN = function(x) Reduce('-', expand.grid(rep(list(x), 2))))

Or another option is with outer after looping through the columns

apply(data, 2, FUN = function(x) outer(x, x, FUN = '-'))

Upvotes: 5

Related Questions