我正在尝试编写一些简单的Rcpp代码示例.使用Rcpp和inline包装非常容易.
但我很难过如何测试两个字符元素是否相等.以下示例比较了两个字符向量的第一个元素.但我无法编译.
诀窍是什么?
library(Rcpp)
library(inline)
cCode <- '
Rcpp::CharacterVector cx(x);
Rcpp::CharacterVector cy(y);
Rcpp::LogicalVector r(1);
r[0] = (cx[0] == cy[0]);
return(r);
'
cCharCompare <- cxxfunction(signature(x="character", y="character"),
plugin="Rcpp", body=cCode)
cCharCompare("a", "b")
Run Code Online (Sandbox Code Playgroud)
-
==如果两个元素中的一个是常数,则使用的比较完全正常.以下代码编译并给出预期结果:
cCode <- '
Rcpp::CharacterVector cx(x);
Rcpp::LogicalVector r(1);
r[0] = (cx[0] == "a");
return(r);
'
cCharCompareA <- cxxfunction(signature(x="character"), plugin="Rcpp", body=cCode)
cCharCompareA("a")
[1] TRUE
cCharCompareA("b")
[1] FALSE
Run Code Online (Sandbox Code Playgroud) R 具有很好的 wrapper-ish 功能anyNA,可以更快地评估any(is.na(x)). 在 Rcpp 中工作时,可以通过以下方式给出类似的最小实现:
// CharacterVector example
#include <Rcpp.h>
using namespace Rcpp;
template<typename T, typename S>
bool any_na(S x){
T xx = as<T>(x);
for(auto i : xx){
if(T::is_na(i))
return true;
}
return false;
}
// [[Rcpp::export(rng = false)]]
LogicalVector any_na(SEXP x){
return any_na<CharacterVector>(x);
}
// [[Rcpp::export(rng = false)]]
SEXP overhead(SEXP x){
CharacterVector xx = as<CharacterVector>(x);
return wrap(xx);
}
/***R
library(microbenchmark)
vec <- sample(letters, 1e6, TRUE)
vec[1e6] <- NA_character_ …Run Code Online (Sandbox Code Playgroud) 我正在尝试以y第二个可为空向量 ( r)的值是否为条件来评估向量 ( )的总和NA。如果第二个向量r为 NULL,y则应将 的所有值相加。如果 的所有元素r都是NA,则函数应返回 NA。请参阅文本末尾以获得所需的输出。
我首先尝试了以下代码:
library(Rcpp)
cppFunction('double foo(NumericVector y, Rcpp::Nullable<Rcpp::IntegerVector> r = R_NilValue) {
double output = 0;
bool return_na = !Rf_isNull(r);
int y_count = y.size();
for (int i = 0; i < y_count; i++) {
if (Rf_isNull(r) || !R_IsNA(r[i])) {
//// if (Rf_isNull(r) || !R_IsNA(as<IntegerVector>(r)[i])) {
if (!Rf_isNull(r))
Rcout << R_IsNA(as<IntegerVector>(r)[i]) << " - "<< as<IntegerVector>(r)[i] << std::endl;
output = output …Run Code Online (Sandbox Code Playgroud)