[R] how to create a substraction matrix (subtract a row of every column from the same row in other columns)

Ben Bolker bbolker at gmail.com
Thu Sep 13 14:20:12 CEST 2012


csmeredith <csmeredith <at> fs.fed.us> writes:

>

 [snip]

> I want to create a matrix similar to a correlation matrix, but with the
> difference between the two values, like this
> 
> x1   x2         x3         x4          x5
> x1   x2-x1    x3-x1     x4-x1     x5-x1
> x2               x3-x2     x4-x2     x5-x2
> x3                           x4-x3      x5-x3
> x4                                        x5-x4
> x5
> 
> Then I want to convert it back to a data frame with a column that describes
> what columns were used in the calculation, but I would like to only include
> the comparisons that go forward in number. Basically, each number represents
> a year, and I want each comparison to only be listed once, the difference
> between the 1st year the sample was taken and then 2nd year the sample was
> taken. (This would probably entail just taking a portion of the matrix.) .

  [snip]


  You might want to start with (something like)

library(reshape2); subset(melt(outer(x,x,"-")), Var1>Var2)

and then remove redundant rows ...

  I haven't actually tested any of that, but it should get you
started.




More information about the R-help mailing list