[R] adding zeroes after old zeroes in a vector ??

Gabor Grothendieck ggrothendieck at gmail.com
Fri Sep 10 22:13:02 CEST 2010


On Fri, Sep 10, 2010 at 1:51 PM, skan <juanpide at gmail.com> wrote:
>
> Hello
>
> Imagine I have a vector with ones and zeroes
>
> I write it compactly:
> 1111111100001111111111110000000001111111111100101
>
> I need to get a new vector replacing the "N" ones following the zeroes to
> new zeroes.
>
> For example for N = 3
> 1111111100001111111111110000000001111111111100101  becomes
> 1111111100000001111111110000000000001111111100000
>
> I can do it with a for loop but I've read is not a good practice,  How can I
> do it then?
>

Here is a solution using rollapply.zoo.  It makes use of the
development version of zoo in which the rollapply function supports an
additional partial= argument.  It is based on the idea that if any
subsequence starts with 0, ends with 1 and is nondecreasing then its
last element must be replaced with 0.

library(zoo)
# grab development version of rollapply
source("http://r-forge.r-project.org/scm/viewvc.php/*checkout*/pkg/zoo/R/rollapply.R?revision=799&root=zoo")

# test data
z <- zoo(c(1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1))

N <- 3
f <- function(x, xn = tail(x, 1)) if (!x[1] && xn && all(diff(x) >=
0)) 0 else xn
rollapply(z, N+1, FUN = f, align = "right", partial = TRUE)


-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list