【问题标题】:Access dimension names from sp_mat in Rcpp Armadillo从 Rcpp Armadillo 中的 sp_mat 访问维度名称
【发布时间】:2018-08-29 21:59:52
【问题描述】:

我是 Rcpp 的新手,我正在尝试确定如何访问输入的维度名称,以便稍后在脚本中使用它们。具体来说,我试图从 Armadillo 中的稀疏矩阵中获取列名,并使用它们来命名单独对象中的行。

举例说明: 让我们从生成一个平凡的稀疏矩阵开始。

   input_mat <- Matrix::Matrix(sample(c(0,1), 35, replace =T)
                        ,nrow = 5
                        ,ncol = 7
                        ,dimnames = list(LETTERS[1:5], letters[1:7]))

接下来,让我们用它在 Rcpp 中做一些事情。我们将输出一个填充了一些随机数的数字矩阵。输出的 nrow = 输入的 ncol。

cppFunction('NumericMatrix map_columns(arma::sp_mat x, int k) {
              int n = x.n_cols;
              NumericMatrix new_mat = NumericMatrix(n, k);
              for(int i = 0; i < n; i++) {
                for(int j = 0; j < k; j++) {
                    new_mat(i,j) = rand() % 100 + 1; 
                }
              }
              rownames(new_mat) = CharacterVector::create("a", "b", "c", "d", "e", "f", "g");
              return(new_mat);
              }', depends = "RcppArmadillo"
              )

map_columns(input_mat, 4)

我不想手动指定 new_mat 的行名,而是想获取 x 的列名并动态分配名称。我尝试访问稀疏矩阵的插槽名称,并尝试以与 R 中相同的方式分配它们,但没有运气。

我猜我犯了一个简单的错误。有人可以帮我解决这个问题吗?任何帮助将不胜感激。

【问题讨论】:

    标签: rcpp armadillo


    【解决方案1】:

    我不知道在转换为犰狳对象后访问 S4 插槽的可能性,但是,您可以将稀疏矩阵作为 S4 对象传递给函数并显式处理转换:

    input_mat <- Matrix::rsparsematrix(5, 7, 0.2)
    input_mat@Dimnames <- list(LETTERS[1:5], letters[1:7])
    
    
    Rcpp::cppFunction('NumericMatrix map_columns(Rcpp::S4 y, int k) {
                  arma::sp_mat x = Rcpp::as<arma::sp_mat>(y);
                  int n = x.n_cols;
                  NumericMatrix new_mat = NumericMatrix(n, k);
                  for(int i = 0; i < n; i++) {
                    for(int j = 0; j < k; j++) {
                        new_mat(i,j) = rand() % 100 + 1; 
                    }
                  }
                  Rcpp::List dimnames = y.slot("Dimnames");
                  Rcpp::CharacterVector colnames = dimnames[1];
                  rownames(new_mat) = colnames;
                  return(new_mat);
                  }', depends = "RcppArmadillo"
    )
    
    map_columns(input_mat, 4)
    

    请注意,我正在创建一个稀疏矩阵,而不是在您的示例代码中找到的密集矩阵。

    旁注:不要使用rand()。使用 R 的 RNG,来自 C++11 的 &lt;random&gt; 或 ...

    【讨论】:

    • 有一些与此相关的 Rcpp Gallery 帖子,用于 S4 访问和转换(通常由稀疏矩阵驱动)以及属性设置。
    猜你喜欢
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 2014-03-12
    相关资源
    最近更新 更多