c++ - 将数组发送到 R 函数 (C++)

标签 c++ r

我用 C++ 编写了这个函数:

extern "C"
{

    void add(int* first, int* second, int *n , int* sum)
    {
        for (int i = 0; i< *n; i++)
        {
            sum[i] = first[i] + second[i];
        }


    }
}

还有这个司机:

add <- function(twoColumn)
{
    if(!is.data.frame(twoColumn))stop("twoColumn should be data.frame")

    first <- twoColumn[1]
    second <- twoColumn[2]
    n <- length(first)
    .C("add",first = as.integer(unlist(first)),second = as.integer(unlist(second)),  n = as.integer(n),sum = as.integer(rep(0,n)))$sum


}

但 R 输出只是数据框第一行总和的数字。

最佳答案

我不知道问题出在哪里,但可以提供代码的(有点过于雄心勃勃的)工作版本。它需要你封装功能,并且是这样工作的:

src/add.cpp:

SEXP add(SEXP Rx, SEXP Ry){
    SEXP xy_sum;
    int i;
    PROTECT(xy_sum = allocVector(REALSXP, 1));
    for(i = 0; i < length(Rx); i++){
        REAL(xy_sum)[i] = REAL(Rx)[i] + REAL(Ry)[i];
    }
    UNPROTECT(1);
    return xy_sum;
}

scr/add.h:

#ifndef _add_ADD_H
#define _add_ADD_H

#include <R.h>
#include <Rdefines.h>

extern "C" SEXP add(SEXP Rx, SEXP Ry);

#endif

R/add.R:

add <- function(x, y){
    if(length(x) != length(y)) stop("Vectors must be of the same length.")
    # coerce into numeric in case the user supplied something silly
    .Call("add", PACKAGE="add", as.numeric(x), as.numeric(y))
}

R/zzz.R:

.onLoad <- function(lib, pkg){
    library.dynam("add", pkg, lib)
}

关于c++ - 将数组发送到 R 函数 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11096422/

相关文章:

database - 使用 bash 脚本从在线数据库下载文件

r - 一个类轮想要 : Create data frame and give colnames: R data. 帧(..., colnames = c ("a", "b", "c"))

r - 在函数输出中打印数据框名称

c++ - 如何在 mac os x 10.9.5 上构建 QuantLib

C++ 寻找流数据的最大值

c++ - CMake:target_include_* 中的 *.hpp 和 *.cpp

r - 将 iframe Amazon Associate Link 嵌入到 .md 文件 R

c++ - struct int数据类型不适用于关系运算符

c++ - 运行 GCC/G++ 时,如何告诉它安装位置

r - 使用 R 中的 ROCR 包计算精度