Home > Mobile >  What's the most efficient way to generate a vector of values from -2 to 5 with a difference of
What's the most efficient way to generate a vector of values from -2 to 5 with a difference of

Time:12-22

What's the most efficient way to generate a vector of values from -2 to 5 with a difference of 0.1 in R?

CodePudding user response:

Use seq function,

seq(-2, 5, 0.1)

CodePudding user response:

seq.int() is known to be much faster than seq().

seq.int(-2, 5, .1)

Alternatively, we could try a while loop,

(5 - -2)/.1   1  ## calculate number of steps
# [1] 71

i <- 1; r <- s <- -2  ## define starting values
while (i < 71L) {
  s <- s   .1
  r[i   1] <- s
  i <- i   1
}
print(r)

an even try integers.

ii <- 1L; ri <- si <- -20L  ## define starting values
while (ii < 71L) {
  si <- si   1L
  ri[ii   1L] <- si
  ii <- ii   1L
}
print(ri*.1)

Looking at the benchmark (sequence from -2 to 1e5 used), the while loops are faster than seq() (ignoring the time to define the start values!!), but seq.int() is still faster.

Unit: milliseconds
      expr      min       lq      mean    median        uq       max neval cld
       seq 8.857606 9.468344 11.579976 10.448676 12.225051  49.10238  1000   c
   seq.int 1.351898 1.495189  2.187937  1.720612  2.243119  25.16653  1000 a  
     While 3.777003 3.946604  4.797641  4.164015  4.365438 476.62461  1000  b 
 While.int 3.775510 3.930066  4.709157  4.155621  4.348228 410.80900  1000  b 
  •  Tags:  
  • r
  • Related