创建bool向量
r - Rcpparmadillo c++ create bool vector
我试图将bool向量作为参数传递给使用Rcpparmadillo的函数。下面是一个愚蠢的例子:
// [[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;
}
这里建议使用mat<unsigned char>
类型,但不适合我。我也试过uvec
和std::vector<bool>
,但也不起作用。使用Rcpparmadillo
传递逻辑向量作为参数的最佳方法是什么?
您需要Armadillo的uvec
—它没有bool
类型。这是你的代码的一个重新格式化的版本*使用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)
*/
如果我们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>
相关文章:
- 写入向量<向量<bool>>
- 如何告诉自动推断向量<bool>元素的非引用类型
- 如何从C++中的值向量构造整数<bool>值
- 如何诊断保存和加载位向量(std::vector)的奇怪行为<bool>?
- 在 lambda 表达式中自动推导出的类型是什么,用于修改 bool 类型的向量(特殊容器)
- 创建一个类型bool的向量,其中所有值均可初始化为true
- 根据向量<bool>修改字符的位
- 我们可以使用<bool>自定义分配器创建法线向量吗?
- C++ 避免向量<bool>实例化
- 排列解析器到向量<bool>,通过匹配
- 比较两个向量<bool>与SSE的关系
- 由 int 初始化的 can 向量<bool>
- 排序向量<向量<bool>>基于向量<bool>的内容
- 将向量<bool>转换为十进制(作为字符串)
- 将二进制文件读入位集或向量<bool>
- 在访问向量<bool>中元素的地址时获取临时地址
- MSVS 2015:向量<bool>没有'data'成员
- 将 stl 向量<bool>转换为布尔 * 数组的快速方法
- 向量<bool>常量成员函数
- 向量<bool>::运算符[] 不当行为?