Converting decimal to binary in R
On Sat, 14 Dec 2013, ???????? wrote:
i have write a function to convert decimal number into binary number in R.
dectobin<-function(x){
as.numeric(intToBits(x))->x1
paste(x1,collapse="")->x2
as.numeric(gsub("0+$","",x2))->x3
return(as.character(x3))}
dectobin can get right result ,it is so long ,is there a build-in
function to do ?
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
}
[[alternative HTML version deleted]]
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