[R] question to make a vector without loop
William Dunlap
wdunlap at tibco.com
Fri Feb 26 17:02:58 CET 2010
> -----Original Message-----
> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of
> khazaei at ceremade.dauphine.fr
> Sent: Friday, February 26, 2010 7:23 AM
> To: r-help at r-project.org
> Subject: [R] question to make a vector without loop
>
> Hello all,
>
> I want to define a vector like w[k+1]=w[k]*a/(b+k) for
> k=1,...,N-1 without
> use loop. Is it posible to do in R?
It would be nice to see your loopy solution.
However, you could use cumprod (cumulative
products):
c(w[1], w[1] * cumprod(a/(b+seq_len(N-1)))
E.g.,
> w<-7
> a<-2
> b<-1
> for(k in 1:9) w[k+1] <- w[k] * a / (b+k)
> w
[1] 7.0000000000 7.0000000000 4.6666666667 2.3333333333 0.9333333333
[6] 0.3111111111 0.0888888889 0.0222222222 0.0049382716 0.0009876543
> c(w[1], w[1]*cumprod(a/(b+seq_len(9))))
[1] 7.0000000000 7.0000000000 4.6666666667 2.3333333333 0.9333333333
[6] 0.3111111111 0.0888888889 0.0222222222 0.0049382716 0.0009876543
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
>
> Regards
>
> khazaei
>
> ______________________________________________
> 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