Re: [R] Help on vectorizing

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Sun, 09 Mar 2008 20:08:26 -0400

Try this:

r <- unlist(sapply(x, function(x) c(rep(0, x), 1))) x2 <- diff(c(0, which(r==1))) - 1
identical(x, x2)

On Sun, Mar 9, 2008 at 7:55 PM, remko duursma <remkoduursma_at_hotmail.com> wrote:
>
> Dear R-helpers,
>
> I have two problems that I don't know how to vectorize (but would like to because my current solution is slow).
>
> # 1.
> #I have a vector x:
>
> x <- c(3, 0, 1, 0, 2, 2, 2, 0, 4, 2)
>
> #I want this translated into a new vector based on x,so that each element of x
> #is the number of zeroes, followed by a 1. The new vector would look like:
>
> #> r# [1] 0 0 0 1 1 0 1 1 0 0 1 0 0 1 0 0 1 1 0 0 0 0 1 0 0 1
>
> # I only found a solution that loops, and it's a bit ugly:
> r <- c()for(i in 1:length(x))r <- c(r, rep(0,pmax(0,x[i])),1)
>
>
> # 2.
> # The other way around, so that we have the vector r, and want to find x.
> # I have a (very) ugly solution:
> chars <- paste(r,collapse="")zeros <- strsplit(chars,"1")x <- nchar(zeros[[1]])
>
>
>
> Thanks for your help!
>
> Remko Duursma
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



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. Received on Mon 10 Mar 2008 - 00:12:50 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 10 Mar 2008 - 05:30:21 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive