Skip to content
Prev 334414 / 398506 Next

Converting decimal to binary in R

On Sat, 14 Dec 2013, ???????? wrote:

            
I don't know of one. The below function is roughly twice as fast as yours 
and it works on an entire vector of values at once (but it still uses a 
for loop to do so).

decToBinStr <- function(x) {
   l <- floor( log( x, 2 ) ) + 1
   v <- as.logical( intToBits( x ) )
   vc <- rep( "0", length( v ) )
   vc[ v ] <- "1"
   m <- matrix( vc, ncol=length( x ) )
   result <- rep( NA, length( x ) )
   for ( idx in seq.int( length( x ) ) ) {
     result[ idx ] <- paste( m[ seq.int( l[ idx ], 1 ), idx ], collapse="" )
   }
   result
}
Per the Posting Guide, please post in plain text.

---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                       Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k