【问题标题】:Rcpp: how to combine the R function and Rcpp function together to make a packageRcpp:如何将R函数和Rcpp函数组合在一起制作一个包
【发布时间】:2021-02-25 22:54:14
【问题描述】:

假设我在名为 test.cpp 的文件中有以下 c++ 代码

#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;
}

我知道用下面的命令,我可以拥有自己的包

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

但是,如果我想将以下调用 Rcpp 函数的 R 函数合并到包中怎么办

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 )
}

我该怎么做?

【问题讨论】:

    标签: r rcpp r-package rcpp11


    【解决方案1】:

    所以你问如何制作一个 R 包?有很多很好的教程。

    第一个近似值:

    • 将您的文件复制到文件R/random.R
    • 处理函数的帮助文件,可以通过编写man/random.Rd 或通过学习包roxygen2 手动处理
    • 确保您知道 NAMESPACE 的用途以及 DESCRIPTION 是正确的

    【讨论】:

      猜你喜欢
      • 2014-06-25
      • 2013-11-13
      • 1970-01-01
      • 2016-08-26
      • 2020-11-13
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      相关资源
      最近更新 更多