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] 50.81701

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 to total = total + x[i].
  • other in-place operators are -=, *=, and /=

To check for the fastest way we can use:

?bench::mark
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.03µs   2.06µs   474696.        0B        0
#> 2 sumC(x)      4.43µs    4.5µs   214136.        0B        0
#> 3 sumR(x)     20.09µs  20.55µs    47211.        0B        0