# [R] Minimizing Computational Time

R. Michael Weylandt michael.weylandt at gmail.com
Tue Oct 23 14:45:09 CEST 2012

```On Tue, Oct 23, 2012 at 11:06 AM, Naser Jamil <jamilnaser79 at gmail.com> wrote:
> Dear R-users,
> May I seek some suggestions from you. I have a long programme written in R
> with several 'for' loops inside. I just want to get them out by any elegant
> way (if there is!) to reduce the computational time of the main programme.
> For instance, is there any smart way for the following programme that will
> lessen time?
>
> ---------------------------------------------------------------------------------------------------------------
>
> dose<-seq(0,10,.5)
> alpha1<--4
> beta1<-0.5
> alpha2<--6
> beta2<--.7
>
> psi1<-function(alpha1,beta1,alpha2,beta2,d){
> z1<-exp(alpha1+beta1*d)
> z2<-exp(alpha2+beta2*d)
> z1/((1+z1)*(1+z2))
>                                                                       }
> psi2<-function(alpha2,beta2,d) {
> z2<-exp(alpha2+beta2*d)
> z2/(1+z2)
>                                                  }
> psi1.hat=c()
> psi2.hat=c()
> for (i in 1:length(dose)){     # just want to avoid this 'for' loop
> d<-dose[i]
> psi1.hat[i]<-psi1(alpha1,beta1,alpha2,beta2,d)
> psi2.hat[i]<-psi2(alpha2,beta2,d)
>                                      }
>

Yes, just omit it and it all works magically:

psi1.hat <- psi1(alpha1, beta1, alpha2, beta2, dose)
psi2.hat <- psi1(alpha1, beta1, alpha2, beta2, dose)

Note that you also don't need to initialize psi1.hat, psi2.hat in this
circumstance.

I think you would greatly benefit from re-reading the bit of the
"Introduction to R" manual which covers vectorization.

Cheers,
Michael

> print(psi1.hat)
> print(psi2.hat)
>
> ------------------------------------------------------------------------------------------------------------
>
> Many  thanks for your kind attention.
>
> Regards,
> Jamil.
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help