开发者

in R, how to retrieve a complete matrix using combn?

开发者 https://www.devze.com 2023-02-22 21:31 出处:网络
My problem, removing the specific purpose,seems like this: how to transform a combination like this: first use combn(letters[1:4], 2) to calculate the combination

My problem, removing the specific purpose, seems like this: how to transform a combination like this: first use combn(letters[1:4], 2) to calculate the combination

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,] "a"  "a"  "a"  "b"  "b"  "c" 
[2,] "b"  "c"  "d"  "c"  "d"  "d" 

use each column to obtain another data frame:

   [,1] [开发者_开发技巧,2] [,3] [,4] [,5] [,6]
[1,] 1    2    3    4   5     6

elements are obtained, for example: the first element, from the first column of the above dataframe

then How can i transform the above dataframe into a matrix, for example result, things like:

   a   b   c  d
a  0   1   2  3
b  1   0   4  5
c  2   4   0  6
d  3   5   6  0

the elements with same col and row names will have zero value where others corresponding to above value


Here is one way that works:

inputs <- letters[1:4]
combs <- combn(inputs, 2)
N <- seq_len(ncol(combs))
nams <- unique(as.vector(combs))
out <- matrix(ncol = length(nams), nrow = length(nams))
out[lower.tri(out)] <- N
out <- t(out)
out[lower.tri(out)] <- N
out <- t(out)
diag(out) <- 0
rownames(out) <- colnames(out) <- inputs

Which gives:

> out
  a b c d
a 0 1 2 3
b 1 0 4 5
c 2 4 0 6
d 3 5 6 0

If I had to do this a lot, I'd wrap those function calls into a function.

Another option is to use as.matrix.dist() to do the conversion for us by setting up a "dist" object by hand. Using some of the objects from earlier:

## Far easier
out2 <- N
class(out2) <- "dist"
attr(out2, "Labels") <- as.character(inputs)
attr(out2, "Size") <- length(inputs)
attr(out2, "Diag") <- attr(out2, "Upper") <- FALSE
out2 <- as.matrix(out2)

Which gives:

> out2
  a b c d
a 0 1 2 3
b 1 0 4 5
c 2 4 0 6
d 3 5 6 0

Again, I'd wrap this in a function if I had to do it more than once.


Does it have to be a mirror matrix with zeros over the diagonal?

combo <- combn(letters[1:4], 2)
in.combo <- matrix(1:6, nrow = 1)
combo <- rbind(combo, in.combo)
out.combo <- matrix(rep(NA, 16), ncol = 4)
colnames(out.combo) <- letters[1:4]
rownames(out.combo) <- letters[1:4]

for(cols in 1:ncol(combo)) {
    vec1 <- combo[, cols]
    out.combo[vec1[1], vec1[2]] <- as.numeric(vec1[3])
}

> out.combo
   a  b  c  d
a NA  1  2  3
b NA NA  4  5
c NA NA NA  6
d NA NA NA NA
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号