[英]Calculate / Translate vector of numbers in binary matrix / vector in R
我如何自動構建一個矩陣,將vector <- c(1,2,3)
的排列轉換為某種二進制格式? 像這樣:
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
雖然我想要的不是 3 個,而是 7 個值。
一種方法是
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
這是一個將任何向量轉換為適當的二進制矩陣的函數,
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))
這使,
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
這是一個非常快的單行代碼:
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
[-1, ]
是刪除所有零的行。 這一行代表冪集中的空集。 實際上,從技術上講,您要求的是從向量的冪集(當然減去空集)到二進制矩陣的映射。
如果您真的希望row.names
成為實際的排列,您可以使用rje
包中的powerSet
函數。 觀察:
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
*免責聲明:我是RcppAlgos
的作者
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.