Antonello - 1 year ago 59

R Question

`f <- function(n){`

s <- 0

for (i in 1:n){

s <- s + (i/2)

}

print(s)

}

The tricky part is of course that

`s`

[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)`

`sum(seq_len(n)/2)`

For comparison, the same function (with n=1000000000) in Julia takes 38 seconds (0.87 defining the type of

`s`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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**