Quite simply:
f <- function(num,len){
num*(-1)**(0:len)
}
> f(1,5)
[1] 1 -1 1 -1 1 -1
> f(3,5)
[1] 3 -3 3 -3 3 -3
> f(-1,5)
[1] -1 1 -1 1 -1 1
This is quite efficient at at the same time it makes sense as a numeric function. However, the most efficient one by an order of magnitude is the rep
approach, specially as n
get larger.
> n <- 10000
> microbenchmark::microbenchmark(
+ rep(c(1, -1), length.out = n),
+ c(-1, 1)[((1:n)%%2 == 1)+1],
+ ifelse((1:n)%%2,1,-1),
+ (-1)**(0:n)
+ )
Unit: microseconds
expr min lq mean median uq max neval
rep(c(1, -1), length.out = n) 14.358 14.8565 15.16934 15.1425 15.3390 18.651 100
c(-1, 1)[((1:n)%%2 == 1) + 1] 238.995 240.0120 242.85757 240.7370 241.5830 312.495 100
ifelse((1:n)%%2, 1, -1) 311.653 314.0150 422.23417 315.2280 317.3465 5341.466 100
(-1)^(0:n) 211.948 212.6665 215.50381 213.2490 213.6770 339.639 100