创建给定数字的二进制向量

时间:2014-11-14 08:26:05

标签: r

有没有一种简单的方法来获取数字的二进制向量?我想指定要使用的位数。

因此,例如,4位中的4位将返回c(F,T,F,F)或6位c(F,F,F,T,F,F)

所以我想要创建的是这样的,但有大约8个因素(tx

library(ggplot2)
tx <- factor(c("a", "b", "c"))
ty <- rep(0:(2 ^ length(tx) - 1), each=length(tx))
df <- data.frame(x=tx, y=ty)
df$z <- c(F,F,F,F,F,T,F,T,F,F,T,T,T,F,F,T,F,T,T,T,F,T,T,T)
ggplot(df, aes(x, y, fill = z)) + geom_raster()

有人可以帮我吗?

2 个答案:

答案 0 :(得分:2)

尝试

as.logical(rep(4,each=4)%/% (2^(3:0)) %%2)
#[1] FALSE  TRUE FALSE FALSE

as.logical(rep(4,each=6)%/% (2^(5:0)) %%2)
#[1] FALSE FALSE FALSE  TRUE FALSE FALSE


v1 <- c(4,9,10,0,5)
!!matrix(rep(v1,each=6)%/% (2^(5:0)) %%2, ncol=6, byrow=TRUE)
#      [,1]  [,2]  [,3]  [,4]  [,5]  [,6]
#[1,] FALSE FALSE FALSE  TRUE FALSE FALSE
#[2,] FALSE FALSE  TRUE FALSE FALSE  TRUE
#[3,] FALSE FALSE  TRUE FALSE  TRUE FALSE
#[4,] FALSE FALSE FALSE FALSE FALSE FALSE
#[5,] FALSE FALSE FALSE  TRUE FALSE  TRUE

答案 1 :(得分:2)

这样的事情似乎也是有效的:

ff = function(x, n) rev(as.logical(intToBits(x))[seq_len(n)])

ff(4, 4)
#[1] FALSE  TRUE FALSE FALSE
ff(4, 6)
#[1] FALSE FALSE FALSE  TRUE FALSE FALSE

Vectorize(ff)(c(4,9,10,0,5), 6)  ##to compare with akrun's
#      [,1]  [,2]  [,3]  [,4]  [,5]
#[1,] FALSE FALSE FALSE FALSE FALSE
#[2,] FALSE FALSE FALSE FALSE FALSE
#[3,] FALSE  TRUE  TRUE FALSE FALSE
#[4,]  TRUE FALSE FALSE FALSE  TRUE
#[5,] FALSE FALSE  TRUE FALSE FALSE
#[6,] FALSE  TRUE FALSE FALSE  TRUE
相关问题