Hi Lydia,

I compared my ratio function with Dimitris and Phil's suggestions. Please do
NOT use my approach because it's painfully slow for a large vector (as Phil
told me). Here is why (using Win XP SP2, Intel Core- 2 Duo 2.4 GHz, R 2.7.0
Patched):


# Vector
x=rnorm(100000,0,1)

# Suggestion
new.ratio=function(x) x[2:length(x)]/x[1:(length(x)-1)]

# My horrible function
my.ratio=function(x){
 temp=NULL
 for (n in 1:length(x)) temp=c(temp,x[n]/x[n-1])
 temp
 }

 # System time
t=system.time(my.ratio(x))
tnr=system.time(new.ratio(x))
 t
   user  system elapsed
  38.79    0.06   39.31
 tnr
   user  system elapsed
      0       0       0


Thanks to all,

Jorge



On Mon, May 12, 2008 at 11:15 AM, Phil Spector <[EMAIL PROTECTED]>
wrote:

> Another alternative would be to take advantage of R's vectorization:
>
>  x=c(1,2,3,2,1,2,3)
> > x[2:length(x)]/x[1:(length(x)-1)]
> >
> [1] 2.0000000 1.5000000 0.6666667 0.5000000 2.0000000 1.5000000
>
> The solution using your ratio function will be painfully slow
> for a large vector.
>
>                                       - Phil Spector
>                                         Statistical Computing Facility
>                                         Department of Statistics
>                                         UC Berkeley
>                                         [EMAIL PROTECTED]
>
>

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