Rcpp - 无法访问 StrinvgVector 的元素

Rcpp - can't access elements of StrinvgVector

http://gallery.rcpp.org/articles/working-with-Rcpp-StringVector/

我使用上面的 link 来尝试,因为我想在 R

中使用字符串或字符向量

然而 Rcpp 出于某种原因连接向量的元素我正在使用 Rcout 试图了解发生了什么但我不知道它是什么:

cppFunction('CharacterVector test(NumericMatrix h, NumericMatrix nt, StringVector d, int r){

            CharacterVector m(h.ncol());
            Function f("paste0");
            for(int i = 0; i < d.size(); i++){
              Rcout << d[i];
            }

            return m;
            }')

h <- matrix(0,nrow=2, ncol =2)
colnames(h) <- c("A", "B")
nt <- matrix(0,nrow=2, ncol =2)

d <- c("2019-03", "2014-04")
test(h, nt, d, 1)

Rcout 的输出是:

2019-032014-04[1] "" ""

代替:

"2019-03" "2014-04"

为什么会这样?

如果您希望在发送到 Rcpp::Rcout 的每个元素后有一个 space,您必须这样告诉它。你需要改变

Rcout << d[i];

Rcout << d[i] << " ";

此外,由于 hrbrmstr 的评论,我现在注意到,您还需要在打印每个元素时在它们周围加上引号。同样,如果你想要引号,你必须告诉 Rcout,它不会自动发生。然后,您将上述行进一步修改为

Rcout << "\"" << d[i] << "\" ";

我还会在函数结束前添加一个新行。那么,让我们比较一下;我的 C++ 代码在文件 so-answer.cpp:

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
CharacterVector test(NumericMatrix h, NumericMatrix nt, StringVector d, int r){

    CharacterVector m(h.ncol());
    Function f("paste0");
    for(int i = 0; i < d.size(); i++){
        Rcout << d[i];
    }

    return m;
}

// [[Rcpp::export]]
CharacterVector test2(NumericMatrix h, NumericMatrix nt, StringVector d, int r){

    CharacterVector m(h.ncol());
    Function f("paste0");
    for(int i = 0; i < d.size(); i++){
        Rcout << "\"" << d[i] << "\" ";
    }

    Rcout << "\n";

    return m;
}

/*** R
h <- matrix(0,nrow=2, ncol =2)
colnames(h) <- c("A", "B")
nt <- matrix(0,nrow=2, ncol =2)

d <- c("2019-03", "2014-04")
test(h, nt, d, 1)
test2(h, nt, d, 1)
*/

然后当我使用 Rcpp::sourceCpp() 编译并暴露给 R 时:

Rcpp::sourceCpp("so-answer.cpp")
#> 
#> > h <- matrix(0,nrow=2, ncol =2)
#> 
#> > colnames(h) <- c("A", "B")
#> 
#> > nt <- matrix(0,nrow=2, ncol =2)
#> 
#> > d <- c("2019-03", "2014-04")
#> 
#> > test(h, nt, d, 1)
#> 2019-032014-04[1] "" ""
#> 
#> > test2(h, nt, d, 1)
#> "2019-03" "2014-04" 
#> [1] "" ""

reprex package (v0.2.1)

于 2018-11-23 创建

我还会注意到,我很清楚所有多余的代码是做什么用的,但我只是把它留在里面了。