在 rcpp 中使用 StringMatrix 或 CharacterMatrix 对象时如何使用子字符串?

How to use substring when working with a StringMatrix or CharacterMatrix object in rcpp?

使用 rcpp 时,我试图在 CharacterMatrix 或 StringMatrix 对象上使用子字符串,如下所示:

test <- cxxfunction(signature(), plugin = "Rcpp", body = '
+                     Rcpp::CharacterMatrix v(1,1);
+                     v(0,0) = "Hello";
+                     v(0,0) = v(0,0).substr(0,4);
+                     return v;')

但是当我运行这个的时候,我得到了错误:

Error in compileCode(f, code, language = language, verbose = verbose) : 
  Compilation ERROR, function(s)/method(s) not created! file80c3f1e86e5.cpp:33:37: error: no member named 'substr' in 'Rcpp::internal::string_proxy<16>'
                    v(0,0) = v(0,0).substr(0,4);
                             ~~~~~~ ^
1 error generated.
make: *** [file80c3f1e86e5.o] Error 1
In addition: Warning message:
running command '/Library/Frameworks/R.framework/Resources/bin/R CMD SHLIB file80c3f1e86e5.cpp 2> file80c3f1e86e5.cpp.err.txt' had status 1 

如何在 CharacterMatrix 中的某个元素上使用子字符串?有替代品吗?

类似于@nrussell 的回答,但更明确一些——首先创建一个 string,然后在其上使用 substr()

代码

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
std::string getsubstr(CharacterMatrix M) {
  std::string s = as<std::string>(M(0,0));
  return s.substr(0,4);
}

/*** R
getsubstr(matrix(c("Hello", "world", "brown", "fox"), 2, 2))
*/

运行它

R> sourceCpp("/tmp/charmat.cpp")

R> getsubstr(matrix(c("Hello", "world", "brown", "fox"), 2, 2))
[1] "Hell"
R>