[R] flip certain bits in vector

Esmail esmail.js at gmail.com
Sun Apr 19 21:24:48 CEST 2009


I have a string of binary values, and I would like to flip certain
bits in a set of positions.

Let's say the

vector p contains position [1, 3, 5, 7]
vector b contains bits   [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
result r should be       [0, 1, 0, 0, 0, 0, 0, 0, 1, 0]

in pseudo code this would be something like

---

r = c()

for (i in 1:10)
   if (i in p)
      r = c(r, flip[i])

r
----

doesn't work :-)  R doesn't like the if statement.

Is there a nice, concise way to do this? The vector contents and
size will vary, but length of p <= b.

Thanks,
Esmail




More information about the R-help mailing list