How to create a postive and negative sequence

Viewed 155

I'm currently working on r to bring myself upto scratch. Trying to create a sequence which is

(-10,10,100,100,1000,1000)

My first question is how do I create a sequence that alternates between positive and negative

Secondly how do I create a sequence that multiplies itself by 10 every x amount of numbers.

2 Answers

You can use rep and cumprod creating a sequence that multiplies itself by 10 and multiply with c(-1,1) to alternates between positive and negative:

rep(cumprod(rep(10, 3)), each=2) * c(-1, 1)
#[1]   -10    10  -100   100 -1000  1000

Another idea can be,

rep(10^seq(3), each = 2) * c(-1, 1)
#[1]   -10    10  -100   100 -1000  1000

Just adding a benchmark. Turns out, cumprod is fast

microbenchmark(sotos = rep(10 ^ seq(30), each = 2) * c(-1, 1), 
               GKi = rep(cumprod(rep(10, 30)), each = 2) * c(-1, 1))
Unit: microseconds
  expr   min    lq    mean median    uq    max neval
 sotos 6.911 7.212 7.83658  7.512 7.513 30.348   100
   GKi 1.502 1.803 2.03470  1.804 2.104 11.118   100
Related