71

How do I generate a vector with a specified increment step (e.g. 2)? For example, how do I produce the following

0  2  4  6  8  10
nbro
  • 15,395
  • 32
  • 113
  • 196
LostLin
  • 7,762
  • 12
  • 51
  • 73

3 Answers3

110

Executing seq(1, 10, 1) does what 1:10 does. You can change the last parameter of seq, i.e. by, to be the step of whatever size you like.

> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability 
> [1]  0  2  4  6  8 10
nbro
  • 15,395
  • 32
  • 113
  • 196
John
  • 23,360
  • 7
  • 57
  • 83
8

You can use scalar multiplication to modify each element in your vector.

> r <- 0:10 
> r <- r * 2
> r 
 [1]  0  2  4  6  8 10 12 14 16 18 20

or

> r <- 0:10 * 2 
> r 
 [1]  0  2  4  6  8 10 12 14 16 18 20
nbro
  • 15,395
  • 32
  • 113
  • 196
Travis Nelson
  • 2,590
  • 5
  • 28
  • 34
5

The following example shows benchmarks for a few alternatives.

library(rbenchmark) # Note spelling: "rbenchmark", not "benchmark"
benchmark(seq(0,1e6,by=2),(0:5e5)*2,seq.int(0L,1e6L,by=2L))
##                     test replications elapsed  relative user.self sys.self
## 2          (0:5e+05) * 2          100   0.587  3.536145     0.344    0.244
## 1     seq(0, 1e6, by = 2)         100   2.760 16.626506     1.832    0.900
## 3 seq.int(0, 1e6, by = 2)         100   0.166  1.000000     0.056    0.096

In this case, seq.int is the fastest method and seq the slowest. If performance of this step isn't that important (it still takes < 3 seconds to generate a sequence of 500,000 values), I might still use seq as the most readable solution.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • Edit your answer to explain that [`seq.int`](https://www.rdocumentation.org/packages/base/versions/3.4.3/topics/seq) has, in general, a few restrictions, as the documentation explains. Then you can flag this comment for removal. – nbro Mar 16 '18 at 21:36
  • I'm not sure any of those restrictions are particularly important in this context ... – Ben Bolker Mar 17 '18 at 03:40