Thank you, I will try as soon as possible...
Regards,
Peter

2011/11/3 Mark Leeds <marklee...@gmail.com>

> hi hihi: you're not using the ifelse construct correctly because it's
> already vectorized
> so there's no need to use a loop.
>
> check if below works AND if it's fast enough because I didn't check either
> one. Also,
> i bet someone else can send something better so I would wait anyway. good
> luck.
>
> set.seed(1)
> avec = rnorm(100)
> bvec = rep(0, 100)
> bvec[1]=avec[1]
>
> bveclagged <- c(999,head(bvec,-1))
> bvec <- ifelse((abs(bveclagged + avec) > 1), avec, bveclagged + avec)
>
>
>
>
>
> On Thu, Nov 3, 2011 at 7:10 PM, hihi <v.p.m...@freemail.hu> wrote:
>
>> Dear Members,
>>
>> I work on a simulaton experiment but it has an bottleneck. It's quite
>> fast because of R and vectorizing, but it has a very slow for loop. The
>> adjacent element of a vector (in terms of index number) depends
>> conditionally on the former value of itself. Like a simple cumulating
>> function (eg. cumsum) but with condition. Let's show me an example:
>> a_vec = rnorm(100)
>> b_vec = rep(0, 100)
>> b_vec[1]=a_vec[1]
>> for (i in 2:100){b_vec[i]=ifelse(abs(b_vec[i-1]+a_vec[i])>1, a_vec[i],
>> b_vec[i-1]+a_vec[i])}
>> print(b_vec)
>>
>> (The behaviour is like cumsum's, but when the value would excess 1.0 then
>> it has another value from a_vec.)
>> Is it possible to make this faster? I experienced that my way is even
>> slower than in Excel! Programming in C would my last try...
>> Any suggestions?
>>
>> Than you,
>> Peter
>>
>> ______________________________________________
>> R-help@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.
>>
>
>

        [[alternative HTML version deleted]]

______________________________________________
R-help@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.

Reply via email to