简体   繁体   中英

Calculate / Translate vector of numbers in binary matrix / vector in R

How can a I automatically build a matrix, that converts permutations of a vector <- c(1,2,3) into kind of a binary format? Like this:

x <- matrix(c(1,1,0,0,0,1,0,1,1,0,1,1,0,0,0,1,1,1), ncol = 3)
rownames(x) <- c("1", "1,2", "2", "3", "2,3", "1,2,3")
colnames(x) <- c("1", "2", "3")

x
      1 2 3
1     1 0 0
1,2   1 1 0
2     0 1 0
3     0 0 1
2,3   0 1 1
1,2,3 1 1 1

Though I would like to have not 3, but 7 values.

One approach would be

x <- c(2, 4, 5)
combs <- sapply(1:length(x), combn, x = x)
M <- do.call(rbind, sapply(combs, function(u)
  t(apply(u, 2, function(v) 1 * x %in% v))))
dimnames(M) <- list(unlist(sapply(combs, apply, 2, paste, collapse = ",")), x)
M
#       2 4 5
# 2     1 0 0
# 4     0 1 0
# 5     0 0 1
# 2,4   1 1 0
# 2,5   1 0 1
# 4,5   0 1 1
# 2,4,5 1 1 1

Here is a function that will turn any vector to the appropriate binary matrix,

get_binary <- function(x){
  v1 <- unlist(sapply(seq_along(x), function(i) combn(x, i, toString)))
  mat <- t(sapply(v1, function(i)sapply(x, function(j) as.integer(grepl(j, i)))))
  colnames(mat) <- x
  return(mat)
}

get_binary(c(2, 8, 9))

which gives,

 2 8 9 2 1 0 0 8 0 1 0 9 0 0 1 2, 8 1 1 0 2, 9 1 0 1 8, 9 0 1 1 2, 8, 9 1 1 1

Here is a one-liner that is really fast:

vector <- c(1,2,3)
library(RcppAlgos)
toBinary <- function(v) permuteGeneral(0:1, length(v), TRUE)[-1,]

toBinary(vector)
     [,1] [,2] [,3]
[1,]    0    0    1
[2,]    0    1    0
[3,]    0    1    1
[4,]    1    0    0
[5,]    1    0    1
[6,]    1    1    0
[7,]    1    1    1

The [-1, ] is to remove the row of all zeros. This row would represent the empty set in a power set . In fact, what you are asking for is technically a mapping from the power set of a vector (minus the empty set of course) to a binary matrix.

If you really want the row.names to be the actual permutations, you can use the powerSet function from the rje package. Observe:

library(rje)
nameTest <- toBinary(vector)
row.names(nameTest) <- lapply(powerSet(rev(vector))[-1], sort)

nameTest
           [,1] [,2] [,3]
3             0    0    1
2             0    1    0
c(2, 3)       0    1    1
1             1    0    0
c(1, 3)       1    0    1
c(1, 2)       1    1    0
c(1, 2, 3)    1    1    1

* Disclaimer: I am the author of RcppAlgos

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM