knitr::opts_chunk$set(
    collapse = TRUE,
    comment = "#>",
    fig.path = "man/figures/README-",
    fig.height = 10 * 2 / (1 + sqrt(5)),
    fig.width = 10,
    out.width = "100%"
)

colprods

Travis build status

The goal of colprods is to provide a simple example of how to incorporate Rcpp and RcppArmadillo functions into a package. It does this using various implementations of a function to calculate the column products of a numeric matrix.

Installation

You can install the released version of colprods from Github with:

devtools::install_github("dkidney/colprods")

Simple example

x = matrix(1:9, 3)
x
library(colprods)
colprods_for_loop(x)
colprods_sapply(x)
colprods_apply(x)
colprods_rcpp(x)
colprods_rcpp_rowwise(x)
colprods_arma(x)
as.numeric(colprods_arma(x))

Notice that colprods_arma returns a matrix - this is because I haven't worked out how to coerce a single-row matrix into a vector within the RcppArmadillo code.

Benchmarking

library(dplyr)
library(microbenchmark)
bench = function(x){
    microbenchmark(
        "for_loop" = colprods_for_loop(x),
        "sapply"   = colprods_sapply(x),
        "apply"    = colprods_apply(x),
        "rcpp"     = colprods_rcpp(x),
        "rcpp2"    = colprods_rcpp_rowwise(x),
        "arma"     = colprods_arma(x),
        "arma2"    = as.numeric(colprods_arma(x))
    )
}
print_bench = function(x){
    x %>% 
        summary %>% 
        mutate(mean_rel = mean / min(mean)) %>% 
        mutate(median_rel = median / min(median)) %>% 
        select(expr, mean, median, mean_rel, median_rel, neval) %>% 
        mutate_at(vars(mean, median), round) %>% 
        mutate_at(vars(ends_with("_rel")), funs(round(., 1))) %>% 
        print.data.frame(row.names = FALSE)
}

Tall matrix

nr = 1000
nc = 100
x = matrix(rnorm(nr * nc), nr, nc)
bench_tall = x %>% bench
bench_tall %>% print_bench
bench_tall %>% boxplot(log = TRUE)

Wide matrix

nr = 100
nc = 1000
x = matrix(rnorm(nr * nc), nr, nc)
bench_wide = x %>% bench
bench_wide %>% print_bench
bench_wide %>% boxplot(log = TRUE)


dkidney/colprods documentation built on May 13, 2019, 10:27 a.m.