# [R] (no subject) -- integer to binary

Peter Wolf s-plus at wiwi.uni-bielefeld.de
Thu Feb 5 13:36:32 CET 2004

```meriema.aupetit at free.fr wrote:

>Hello,
>Splus contains the function intbin(x,l).
>
>This function allows to make a conversion from an integer x to a binary of
>length l.
>
>for example
>
>intbin(3,2) returns 11
>
>intbin(3,3) returns 011
>
>Do you know how to do it in R ?
>
>Thank you meriema
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>
>

you can use the following function

encode <- function(number, base) {
# simple version of APL-encode / APL-representation "T", pw 10/02
# "encode" converts the numbers "number" using the radix vector "base"
n.base <- length(base); result <- matrix(0, length(base), length(number))
for(i in n.base:1){
result[i,] <- if(base[i]>0) number %% base[i] else number
number     <- ifelse(rep(base[i]>0,length(number)),
floor(number/base[i]), 0)
}
return( if(length(number)==1) result[,1] else result )
}

paste(encode(c(13), c(2,2, 2, 2, 2)),collapse="")
[1] "01101"
encode(c(13), c(2,2, 2, 2, 2))
[1] 0 1 1 0 1