1

Is there an easy way to get a binary vector of a number? I would like to specify the number of bits to use.

So, for example, 4 in 4bit would return c(F,T,F,F) or in 6bit c(F,F,F,T,F,F).

So what I want to create is something like this but with about 8 factors (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()

Could anybody help me with this?

2 Answers 2

2

Something like this, also, seems valid:

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
Sign up to request clarification or add additional context in comments.

1 Comment

Really nice solution an much easier to read! Thanks for this!
2

Try

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.