繁体   English   中英

将R矩阵传递给低级.C函数,访问数组以更改其值

[英]Passing R matrix to a low-level .C function, accessing the array to change its values

我正在探索基本的.C调用 - 对于C标准体验 - 将R矩阵传递给C函数,将其用作(bi-dims)C数组。 处理(1-dim)向量我没有任何问题,但在这种情况下,我收到了一个核心转储。 如何访问数组的每个单元格并更改其值? 这是正确的方法吗?

我的R矩阵:

> x <- matrix((1:100), ncol=10, nrow=10)
> x
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1   11   21   31   41   51   61   71   81    91
 [2,]    2   12   22   32   42   52   62   72   82    92
 [3,]    3   13   23   33   43   53   63   73   83    93
 [4,]    4   14   24   34   44   54   64   74   84    94
 [5,]    5   15   25   35   45   55   65   75   85    95
 [6,]    6   16   26   36   46   56   66   76   86    96
 [7,]    7   17   27   37   47   57   67   77   87    97
 [8,]    8   18   28   38   48   58   68   78   88    98
 [9,]    9   19   29   39   49   59   69   79   89    99
[10,]   10   20   30   40   50   60   70   80   90   100

这是R函数:

testr <- function(x) {
  d <- as.integer(dim(x))
  r <- .C("testc",
        d,
        x <- as.integer(x))
  return(r[[2]])
}

这是相对C函数:

#include <stdio.h>
#include <math.h>

void testc(int *dim, int *x) {
  int i, j;

  for (j = 0; j < dim[0]; j++) {
    for (i = 0; i < dim[1]; i++) {
      x[j][i] = pow(x[j][i], 2);
    }
  }
}

Alexis Laz发表的评论就是: .C()接口强制将R中的内容转换为矩阵(实质上是:向量加维度属性),直到只有没有维度的向量。

这就是为什么现在推荐使用.Call()以及使用SEXP对象的更丰富界面的众多原因之一。 如果你使用Rcpp,你甚至不需要做任何事情:

R> cppFunction("NumericMatrix doubleMe(NumericMatrix M) { return 2*M; }")
R> doubleMe(matrix(1:9, 3))
     [,1] [,2] [,3]
[1,]    2    8   14
[2,]    4   10   16
[3,]    6   12   18
R> 

这只是定义了一个Rcpp单线程来获取矩阵并返回其值的两倍。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM