Antonello - 1 year ago 59
R Question

# How would you vectorise this for loop in R (s += i/2)?

``````f <- function(n){
s <- 0
for (i in 1:n){
s <- s + (i/2)
}
print(s)
}
``````

The tricky part is of course that
`s`
recursively depends from the previous loop..

[EDIT]

Thank you for your answers. I was just trying to verify the increment in performances using vectorisations in R compared with loops.

With n=1000000000 the above function takes 287 seconds, while both
`sum((1:n)/2)`
and
`sum(seq_len(n)/2)`
return me an error that the system "cannot allocate a vector of size 7.5 Gb"

For comparison, the same function (with n=1000000000) in Julia takes 38 seconds (0.87 defining the type of
`s`
), in C++ 2.48 seconds / 0.87 compiling with optimisation and in Python 98 seconds / 0.88 using numba decorators.

You could do this (in case `n>0`):

``````sum(seq_len(n)/2)

f(10)
#[1] 27.5

sum(seq_len(10)/2)
#[1] 27.5
``````

In case `n<0`:

``````sum((1:n)/2)

n <- -11
f(n)
#[1] -32.5

sum((1:n)/2)
#[1] -32.5
``````

Just a quick benchmarking:

``````library(microbenchmark)
n <- 10000

f1 <- function(n) sum(seq_len(n)/2)
f2 <- function(n){ s <- 0;for (i in 1:n){s <- s + (i/2);};s}

f1(n)==f2(n)
# [1] TRUE
microbenchmark(f1(n), f2(n))

# Unit: microseconds
# expr      min       lq       mean   median       uq      max neval
# f1(n)   20.733   22.235   27.51751   22.836   24.639   82.028   100
# f2(n) 3971.008 4275.383 4517.52582 4484.510 4648.867 5867.272   100
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download