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

Greg Snow Greg.Snow at imail.org
Fri Sep 10 22:20:21 CEST 2010


Here are a couple of options:

> tmp <- strsplit('1111111100001111111111110000000001111111111100101','')
> tmp <- as.numeric(unlist(tmp))
> 
> n <- 3
> 
> tmp2 <- embed(tmp, n+1)
> 
> tmp3 <- tmp
> tmp3[ which( apply( tmp2, 1, function(x) any(x==0) ) ) + n ] <- 0
> 
> paste(tmp3, collapse='')
[1] "1111111100000001111111110000000000001111111100000"
> 
> 
> 
> library(gtools)
> 
> tmpfun <- function(x) {
+ if(any(x==0)) {
+ 0
+ } else {
+ x[length(x)]
+ }
+ }
> 
> tmp4 <- running( tmp, width=4, fun=tmpfun, 
+ allow.fewer=TRUE )
> 
> tmp4 <- unlist(tmp4)
> paste(tmp4, collapse='')
[1] "1111111100000001111111110000000000001111111100000"

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of skan
> Sent: Friday, September 10, 2010 11:52 AM
> To: r-help at r-project.org
> Subject: [R] adding zeroes after old zeroes in a vector ??
> 
> 
> 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?
> 
> cheers
> 
> 
> My vector is a zoo series, indeed, but I guess it doesn't make any
> difference.
> --
> View this message in context: http://r.789695.n4.nabble.com/adding-
> zeroes-after-old-zeroes-in-a-vector-tp2534824p2534824.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> 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.



More information about the R-help mailing list