How to speed up int2bin conversion?
If we assume that you are just convert 8 bits, here is one way with a table lookup. If more than 8 bits, just partition the data and repeat. This sets up a mapping table one time for the lookup. Does 1M in 0.3 seconds on my computer; is this fast enough?
# initialize a matrix with 8 bit binary values
# one time
require(bitops)
b2c <- character(256)
for (i in 0:255){
+ b2c[i + 1] <- sprintf("%1d%1d%1d%1d%1d%1d%1d%1d"
+ , bitAnd(i, 0x80) != 0
+ , bitAnd(i, 0x40) != 0
+ , bitAnd(i, 0x20) != 0
+ , bitAnd(i, 0x10) != 0
+ , bitAnd(i, 0x8) != 0
+ , bitAnd(i, 0x4) != 0
+ , bitAnd(i, 0x2) != 0
+ , bitAnd(i, 0x1) != 0
+ )
+ }
# create vector with 1M values x <- as.integer(1:1e6) int2bin <- function(val)
+ {
+ b2c[bitAnd(val, 0xff) + 1]
+ }
system.time(int2bin(x))
user system elapsed 0.31 0.00 0.32
On Thu, Dec 1, 2011 at 7:14 AM, Jonas J?germeyr <jonasjae at pik-potsdam.de> wrote:
Dear R-help members,
I'm processing a large amount of MODIS data where quality assessment
information is stored as an integer value for each pixel. I have to
converted this number to an 8 digit binary flag to get access to the
stored quality code (e.g. in2bin(165,8) = 1 0 1 0 0 1 0 1).
Unfortunately, I did not manage to find a package providing a fast
function to do so. I need to run this on millions of pixels and thus
wrote the following function.
int2bin <- function(x,ndigits){
? ? base <- array(NA, dim=c(length(x), ndigits))
? ? for(q in 1:ndigits){
? ? ? ? ? base[, ndigits-q+1] <- (x %% 2)
? ? ? ? ? x <- (x %/% 2)
? ? ? }
? ? bin<- apply(base,1,paste,collapse="")
? ? return(bin)
}
Since it is still slow, I have to find a way to express this more
elegantly. I'd really appreciate any help.
Thanking you, with best regards
Jonas J?germeyr
Potsdam Institute for Climate Impact Research
Research Domain II
? ? ? ?[[alternative HTML version deleted]]
______________________________________________ R-help at r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
Jim Holtman Data Munger Guru What is the problem that you are trying to solve? Tell me what you want to do, not how you want to do it.