简体   繁体   中英

How to set some values to NA based on a binary number in R?

I have two datasets y and x that I want to filter y based on x.

   y=c(0.5,0.2,0.1,0.6,0.4,1.3,0.6,2.8)
   x=c(128,64,32,16,2,48,24,6)
   Package HapEstXXR
   x=dec2bin(x)
   x
           128 64 32 16 8 4 2 1
  128   1  0  0  0 0 0 0 0
  64    0  1  0  0 0 0 0 0
  32    0  0  1  0 0 0 0 0
  16    0  0  0  1 0 0 0 0
  2     0  0  0  0 0 0 1 0
  48    0  0  1  1 0 0 0 0
  24    0  0  0  1 1 0 0 0
  6     0  0  0  0 0 1 1 0

As you can see the decimal numbers in x were converted to binary number. So we have eight numbers. from the left to right bit1 bit2 bit3....bit8.

I need to do this: when bit2,bit4, and bit8 in x = 1 , replace the corresponding values in Y by NA .

If your "second" x object is a matrix, you can do:

y[rowSums(x[,c(2,4,8)])==3] <- NA

If you want to put NA in y when either bit2, bit4 or bit8 is 1 (contrary to what is above, which put a NA when all 3 values are 1 ), you can do:

y[rowSums(x[,c(2,4,8)])>=1] <- NA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM