[R] Help on vectorizing

Charles C. Berry cberry at tajo.ucsd.edu
Mon Mar 10 06:11:22 CET 2008


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



More information about the R-help mailing list