[R] Conversion to Binary (base2)

Peter Dalgaard p.dalgaard at biostat.ku.dk
Thu Sep 25 21:50:05 CEST 2008


Jason Thibodeau wrote:
> Hello,
>
> Is there a simple way to take an input, and convert the decimal integers to
> binary? In this case, I have a CSV file, and I need to convert the first
> column of every line to binary.
>
> Thanks.
>
>   
Not really (unless I missed it), sprintf will convert to hex but not 
binary. But you might roll your own as in

 > binary <- function(x) if (all(x<2)) x else paste(binary(x%/%2), x%%2, 
sep="")
 > binary(1:20)
 [1] "00001" "00010" "00011" "00100" "00101" "00110" "00111" "01000" "01001"
[10] "01010" "01011" "01100" "01101" "01110" "01111" "10000" "10001" "10010"
[19] "10011" "10100"

(You can fairly easily do a variant that gets rid of the leading zeros)

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907



More information about the R-help mailing list