[R] flip certain bits in vector

jim holtman jholtman at gmail.com
Sun Apr 19 21:51:17 CEST 2009


try this:

> b <- c(1, 0, 1, 0, 1, 0, 1, 0, 1, 0)
> p <- c(1, 3, 5, 7)
> b[p] <- ifelse(b[p] == 0, 1, 0)
> b
 [1] 0 0 0 0 0 0 0 0 1 0


On Sun, Apr 19, 2009 at 3:24 PM, Esmail <esmail.js at gmail.com> wrote:
> 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
>
> ______________________________________________
> 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
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?




More information about the R-help mailing list