[英]Rcpparmadillo c++ create bool vector
I'm trying to pass a vector of bool as an argument to a function using Rcpparmadillo. 我正在尝试使用Rcpparmadillo将布尔向量作为参数传递给函数。 A silly example looks like this: 一个愚蠢的示例如下所示:
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
// [[Rcpp::export]]
arma::mat myfun(arma::mat A, arma::vec mybool)
{
int n = A.n_rows;
arma::vec B(n);
for(unsigned int i = 0; i < n; ++i)
{
if(mybool.row(i) && i < 10) // mybool.row(i) && throws the error
{
B.row(i) = arma::accu(A.row(i));
}
else
{
B.row(i) = pow(arma::accu(A.row(i)), 0.5);
}
}
return B;
}
Here a mat<unsigned char>
type is suggested but doesn't work for me. 这里建议使用mat<unsigned char>
类型,但不适用于我。 I've tried uvec
and std::vector<bool>
as well but doesn't work either. 我也尝试过uvec
和std::vector<bool>
,但是也不起作用。 What is the best way to pass a logical vector as an argument using Rcpparmadillo
? 使用Rcpparmadillo
将逻辑向量作为参数传递的最佳方法是什么?
You want uvec
from Armadillo -- it does not have a bool
type. 您需要Armadillo的uvec
它没有bool
类型。 Here is a reformatted version of your code which * used uvec
* indexes vectors directly 这是您的代码的重新格式化版本,*使用uvec
*直接索引向量
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
// [[Rcpp::export]]
arma::mat myfun(arma::mat A, arma::uvec mybool) {
unsigned int n = A.n_rows;
arma::vec B(n);
for (unsigned int i=0; i<n; ++i) {
if (mybool[i] && i < 10) {
B[i] = arma::accu(A.row(i)) ;
} else {
B[i] = pow(arma::accu(A.row(i)), 0.5);
}
} //end loop
return B;
}
/*** R
A <- matrix(1:16,4,4)
mybool <- c(FALSE, TRUE, TRUE, FALSE)
myfun(A, mybool)
*/
If we sourceCpp()
this, it runs the R at the bottom for us: 如果我们使用sourceCpp()
,它将在底部运行R:
R> sourceCpp("/tmp/ap13.cpp")
R> A <- matrix(1:16,4,4)
R> mybool <- c(FALSE, TRUE, TRUE, FALSE)
R> myfun(A, mybool)
[,1]
[1,] 5.29150
[2,] 32.00000
[3,] 36.00000
[4,] 6.32456
R>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.