I am trying to get 2 bits of 8-bit value from the cloud mask intermediate product of the NASA. 

The matrix has a dimension of 3200 x 3248. I have to do this conversion for thousands of data sets.

Here is one of the dataset that I want to do this conversion. [dataset](https://drive.google.com/open?id=1jHl4yTmGccHTpPBzIl3zpjB1ZaqHoMr5)

Here is my code: 

```
library(binaryLogic)
test = as.logical(c(0,0))
#n_row <- nrow(cmask_1)
n_row <- 100
cmask_2bits  <- matrix(nrow=n_row, ncol=ncol(cmask_1))

t1 <- Sys.time()

for(i in 1:n_row){
  cmask_2bits[i,] <- sapply(cmask_1[i,], function (x) ifelse(identical(as.logical(as.binary(x, n=8)[5:6]), test), 0, 1))
}

t2 <- Sys.time()

time <- difftime(t2, t1)

t1_mthd2 <- Sys.time()

cmask_2bits_mthd2  <- matrix(nrow=n_row, ncol=ncol(cmask_1))

cmask_2bits_mthd2 <- mapply(function (x) 
ifelse(identical(as.logical(as.binary(x, n=8)[5:6]), test), 0, 1), cmask_1[1:n_row,])

cmask_2bits_mthd2 <- matrix(cmask_2bits_mthd2, nrow=n_row, ncol=ncol(cmask_1))

t2_mthd2 <- Sys.time()

time_mthd2 <- difftime(t2_mthd2, t1_mthd2)

time_mthd2 - time

```

I have tried these two lines of code with `mapply` and `sapply` with `for` loop. I am wondering whether `ifelse` statement can be also improved for faster result. 

My second question is whether this job (getting thousands of matrices) should be done on Hadoop platform or not. 

My result should be like this for the first 10 rows and 10 columns: 

[![enter image description here](https://i.stack.imgur.com/GEPI6.png)](https://i.stack.imgur.com/GEPI6.png)

Any suggestion would be appreciated. 

Edit: As an example, as.binary(15, n=8) gives me the result as 
0 0 0 0 1 1 1 1 as an 8-bit unsigned character. This binary value is read from the right, so that my 2 bits of interest are 3rd and 4th bits, which are 1 1. Since as.binary(15, n=8) gives me a "binary" "logical" vector, I can get these bits by requesting 5th and 6th values of this code result.