[R] extract vector elements of unknown range

William Dunlap wdunlap at tibco.com
Sat Aug 25 18:03:29 CEST 2012


Using system.time() you can check out the performance yourself.  E.g.,
the following compares head(y,-1), y[-length(y)], and y[seq_len(length(y)-1))].

   > y <- 1:10
   > all.equal(head(y,-1), y[-length(y)])
   [1] TRUE
   > all.equal(head(y,-1), y[seq_len(length(y)-1)])
   [1] TRUE
   > system.time(for(i in 1:1e5)head(y,-1))
      user  system elapsed 
      1.53    0.00    1.53 
   > system.time(for(i in 1:1e5)y[-length(y)])
      user  system elapsed 
      0.09    0.00    0.10 
   > system.time(for(i in 1:1e5)y[seq_len(length(y)-1)])
      user  system elapsed 
      0.11    0.00    0.11

Performance may depend on the size or type of the input, so check it on
data similar to what you intend to work with.  E.g., for long vectors the
seq_len approach looks better.
   > y <- runif(1e6)
   > system.time(for(i in 1:100)head(y,-1))
      user  system elapsed 
      1.26    0.25    1.51 
   > system.time(for(i in 1:100)y[-length(y)])
      user  system elapsed 
      1.10    0.36    1.45 
   > system.time(for(i in 1:100)y[seq_len(length(y)-1)])
      user  system elapsed 
      0.67    0.28    0.95

Also note that the relative performance of these idioms may change as R evolves.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Sepp Tannhuber
> Sent: Saturday, August 25, 2012 2:24 AM
> To: r-help at r-project.org
> Subject: Re: [R] extract vector elements of unknown range
> 
> Hi,
> 
> thanks for your quick answers! These solve my problem.
> 
> Now I have another question. I think I can use
>   head(y, -1)
> instead of
>   y[-length(y)]
> 
> Are there differences in terms of performance?
> 
> Best regards
> Joseph
> 
> ______________________________________________
> 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