如何在 R 包中调用 C 函数

How to call a C function in R package

包的名称为 pareto。这是 src 目录中的 .c 文件:

#include <R.h>
#include <math.h>
#include "Rinternals.h"
#include "R_ext/Rdynload.h"

static void dpareto(double *x, double *a, double *b, int *n, int *islog,
                           double *den){
    int length = n[0];
    int i;
    int isLog = islog[0];
    for (i = 0; i < length; i++){
        if (a[i] > 0 && b[i] > 0) {
            if (x[i] > a[i])
                den[i] = log(b[i]) + b[i] * log(a[i]) - (b[i] + 1) * log(x[i]);
            else
                den[i] =  R_NegInf;
            if (!isLog)
                den[i] = exp(den[i]);
        }
        else {
            den[i] = R_NaN;
        }
    }
}

static R_CMethodDef DotCEntries[] = {
    {"dpareto", (DL_FUNC) dpareto, 6},
    {NULL}
};

void R_init_pareto(DllInfo *info)
{
    R_registerRoutines(info, DotCEntries, NULL, NULL, NULL);
}

R目录下,对应的.R文件为:

#' @useDynLib pareto
#' @export
dpareto <- function(x, a, b, log = FALSE) {
    nx <- length(x)
    na <- length(a)
    nb <- length(b)
    n <- max(nx, na, nb)
    if (nx < n) x <- rep(x, length.out = n)
    if (na < n) a <- rep(a, length.out = n)
    if (nb < n) b <- rep(b, length.out = n)
    rt <- .C("dpareto", as.double(x), as.double(a), as.double(b), as.integer(n),
             as.integer(log), den = double(n), PACKAGE="pareto")
    rt$den

}

roxygen 记录后,NAMESPACE 有:

export(dpareto)
useDynLib(pareto)

但是包无法通过检查,并且R不断生成错误消息:

 "dpareto" not available for .C() for package "pareto"
Calls: dpareto -> .C

实在想不通是哪一步出错了

您在 dpareto 函数定义中添加了 static 关键字。这意味着函数不会被导出,所以 R 不会看到它。删除 static 并重试。

小错误。就在 void R_init_pareto 我用错了包名。这么愚蠢的错误。