Vector Input, Scalar output:
sumR <- function(x) {
total <- 0
for (i in seq_along(x)) {
total <- total + x[i]
}
total
}
x<- runif(100)
sumR(x)
#> [1] 51.28519
Translation:
cppFunction('double sumC(NumericVector x) {
int n = x.size();
double total = 0;
for(int i = 0; i < n; ++i) {
total += x[i];
}
return total;
}')
Some observations:
- vector indices start at 0
- The for statement has a different syntax: for(init; check; increment)
- Methods are called with
.
total += x[i]
is equivalent tototal = total + x[i]
.- other in-place operators are
-=
,*=
,and /=
To check for the fastest way we can use:
x <- runif(1e3)
bench::mark(
sum(x),
sumC(x),
sumR(x)
)
#> # A tibble: 3 × 6
#> expression min median `itr/sec` mem_alloc `gc/sec`
#> <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl>
#> 1 sum(x) 2.04µs 2.07µs 472511. 0B 0
#> 2 sumC(x) 4.46µs 4.52µs 211768. 0B 0
#> 3 sumR(x) 20.27µs 20.59µs 48112. 0B 0