nouse
nouse

Reputation: 3461

Creating a matrix from a list of pairwise comparisons

somebody was nice enough to give me a solution from my first problem (using a function on pairwise "all vs all" combinations of a collection of matrices):

library(vegan)
#by Akrun

A <- matrix(sample.int(100, size = 50*50, replace = TRUE), nrow = 50, ncol = 50)
B <- matrix(sample.int(100, size = 50*50, replace = TRUE), nrow = 50, ncol = 50)
C <- matrix(sample.int(100, size = 50*50, replace = TRUE), nrow = 50, ncol = 50)

Obj1 <- vegdist(decostand(A,"standardize",MARGIN=2), method="euclidean")
Obj2 <- vegdist(decostand(B,"standardize",MARGIN=2), method="euclidean")
Obj3 <- vegdist(decostand(C,"standardize",MARGIN=2), method="euclidean")


names1 <- ls(pattern="Obj")
Cmb1 <- combn(names1, 2)
lapply(split(Cmb1, col(Cmb1)), function(x) unlist(mantel(get(x[1]), get(x[2]))[3:4]))

This results in a list of results, for example:

$`1`
 statistic     signif 
0.03006202 0.4070000

There are two questions:

  1. Can i write the two names of the compared objects into the line with "$"? With

    split(Cmb1, col(Cmb1)

the names can be obtained.

  1. Even better, is it possible to somehow create a matrix with n rows and columns for n objects and fill it statistic values?

Thank you for taking your time.

Upvotes: 0

Views: 1986

Answers (1)

Gavin Simpson
Gavin Simpson

Reputation: 174778

Is this what you want...?

(using tmp from

tmp <- sapply(split(Cmb1, col(Cmb1)),
              function(x) unlist(mantel(get(x[1]), get(x[2]))[3:4]))

and noting that I made this an sapply() call so it was easier to extract the statistic data more easily.)

## zero matrix to fill in - change 0 to be what you want on diagonal
mstat <- matrix(0, ncol = 3, nrow = 3)
## directly fill lower triangle of matrix
mstat[lower.tri(mstat)] <- tmp[1, , drop = TRUE]
## need to transpose
tmstat <- t(mstat)
## then fill in lower triangle again, to get correct order
tmstat[lower.tri(tmstat)] <- tmp[1, , drop = TRUE]
## transpose back
mstat <- t(tmstat)
## add on identifiers
colnames(mstat) <- rownames(mstat) <- names1

> mstat
            Obj1        Obj2       Obj3
Obj1  0.00000000 -0.04570113 0.03407708
Obj2 -0.04570113  0.00000000 0.04781475
Obj3  0.03407708  0.04781475 0.00000000

Upvotes: 2

Related Questions