【问题标题】:Call a subset of a vector in Rcpp (not replacing elements)在 Rcpp 中调用向量的子集(不替换元素)
【发布时间】:2018-07-02 23:02:41
【问题描述】:

我想做一个返回向量子集的函数。在 R 中,它是

x <- 1:3 
x[2:3] # return 2nd, 3rd elements

我的Rcpp代码如下,

// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
using namespace Rcpp;

// [[Rcpp::export]]
Rcpp::List subset(arma::vec x){
  return List::create(Named("sub_x") = x.elem(seq(1,2)));
}

但它给了我一个错误

no matching function for call to 'arma::Col<double>::elem(Rcpp::Range)'

我看到很多帖子都在谈论使用 .elem 替换向量中的元素,但据我所知,很难找到适合我的问题的内容。

【问题讨论】:

    标签: r subset rcpp


    【解决方案1】:

    几个cmets:

    1. 您提供了一个向量。你想要一个向量。您编写了一个返回List 的函数。嗯。

    2. 编译器告诉您它确实知道如何将Rcpp::Range 粘贴到犰狳类型中。这是一个很好的提示。

    3. 犰狳记录了 under element accesssubmatrix view

    那就写吧

    // [[Rcpp::export]]
    arma::vec mysubset(arma::colvec x) {
      return x.rows(1,2);
    }
    

    你已经完成了,如下所示:

    R> Rcpp::sourceCpp("~/tmp/so51138571.cpp")
    
    R> x <- 1:3
    
    R> mysubset(x)
         [,1]
    [1,]    2
    [2,]    3
    R> 
    

    这可能也是现有索引问题的重复。

    【讨论】:

    • 谢谢,德克。对于 1,我实际上将这段代码包含在我的 main 函数中,所以我让它返回一个 List,但感谢您指出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 2018-07-23
    相关资源
    最近更新 更多