Rcpp:动态声明ListMatrix的元素(NumericMatrix)

时间:2018-07-08 21:59:51

标签: r rcpp

我想知道如何动态声明ListMatrix的元素(NumericMatrix)。假设我有一个具有动态尺寸的ListMatrix dp1,我想在Rcpp中做以下事情:

#include<Rcpp.h>

// [[Rcpp::export]]
Rcpp::ListMatrix ListMatrixType(Rcpp::ListMatrix dp1){

    // Question: how to declare the type of elements of the ListMatrix 
    // dynamically according to the dimension of dp1?
    // I want to avoid the verbose method as below:
    Rcpp::NumericMatrix dp1_00 = dp1(0,0);
    Rcpp::NumericMatrix dp1_01 = dp1(0,1);
    Rcpp::NumericMatrix dp1_10 = dp1(1,0);
    Rcpp::NumericMatrix dp1_11 = dp1(1,1);

    // then doing something on dp1_00, dp1_01, ..., and others
    dp1_00(0,0) = 100;

    // then update dp1
    dp1(0,0) = dp1_00;
    dp1(0,1) = dp1_01;
    dp1(1,0) = dp1_10;
    dp1(1,1) = dp1_11;

    return dp1;
}

例如,dp1 = matrix(rep(list(matrix(1,100,2)),2 * 2),2,2)。预期的输出与dp1相同。

1 个答案:

答案 0 :(得分:1)

关于“动态声明”,我认为目标是避免多次键入NumericMatrix处理不同的数据类型。

如果是这种情况,则嵌套循环就足够了。

#include<Rcpp.h>

// [[Rcpp::export]]
Rcpp::ListMatrix ListMatrixType_dynamic(Rcpp::ListMatrix x){

    // Dimensions of the List Matrix 
    int n_element_rows = x.nrow();
    int n_element_cols = x.ncol();

    // Loop over each row
    for(int i = 0; i < n_element_rows; ++i) {
        // Loop over each column
        for(int j = 0; j < n_element_cols; ++j) {
            // Retrieve element
            Rcpp::NumericMatrix a = x(i, j);
            // Modify element uniquely by row and column position
            Rcpp::NumericMatrix b = Rcpp::clone(a) + i + j;
            // Store element back into position
            x(i, j) = b; 
        }
    }

    // Return an object back to _R_
    return x;
}