rrcppr-packagercpp11

Rcpp: how to combine the R function and Rcpp function together to make a package


Suppose I have the following c++ code in a file named test.cpp

#include <Rcpp.h>

//[[Rcpp::export]]
Rcpp::NumericMatrix MyAbar (const Rcpp::NumericMatrix & x, int T){
    unsigned int outrows = x.nrow(), i = 0, j = 0;
    double d;
    Rcpp::NumericMatrix out(outrows,outrows);
    // Rcpp::LogicalVector comp;

    for (i = 0; i < outrows - 1; i++){
        Rcpp::NumericVector v1 = x.row(i);
        Rcpp::NumericVector ans(outrows);
        for (j = i + 1; j < outrows ; j ++){
            d = mean(Rcpp::runif( T ) < x(i,j));
            out(j,i)=d;
            out(i,j)=d;
        }
    }
    return out;
}

I know with the following command, I can have my own package

Rcpp.package.skeleton("test",cpp_files = "~/Desktop/test.cpp")

However, what if I want to combine the following R function which call the Rcpp-function into the package

random = function(A, T){
    if (!is.matrix(A)){
        A = Reduce("+",A)/T
    } 
    # global constant and threshold
    n = nrow(A)
    B_0 = 3
    w = min(sqrt(n),sqrt(T * log(n)))
    q = B_0 * log(n) / (sqrt(n) * w)

    A2 = MyAbar(A) 
    diag(A2) <- NA 
    K = A2 <= rowQuantiles(A2, probs=q, na.rm =TRUE)
    diag(K) = FALSE 
    P = K %*% A * ( 1/(rowSums(K) + 1e-10))

    return( (P + t(P))*0.5 )
}

How can i make it?


Solution

  • So you are asking how to make an R package? There are many good tutorials.

    To a first approximation: