Skip to content
Prev 304136 / 398513 Next

extract vector elements of unknown range

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