Re: [R] Help on vectorizing

From: Charles C. Berry <cberry_at_tajo.ucsd.edu>
Date: Sun, 09 Mar 2008 22:11:22 -0700

On Sun, 9 Mar 2008, Gabor Grothendieck wrote:

> Try this:
>
> r <- unlist(sapply(x, function(x) c(rep(0, x), 1)))

And in large problems ( length(x) >> 1000 ), this will be faster still

          r <- rep( rep( 0:1, length(x) ), rbind(x,1) )

HTH, Chuck

> 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.
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry_at_tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901

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 - 05:15:20 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 - 07:30:20 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