简体   繁体   中英

Rcpparmadillo c++ create bool vector

I'm trying to pass a vector of bool as an argument to a function using 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. I've tried uvec and std::vector<bool> as well but doesn't work either. What is the best way to pass a logical vector as an argument using Rcpparmadillo ?

You want uvec from Armadillo -- it does not have a bool type. Here is a reformatted version of your code which * used uvec * indexes vectors directly

// [[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:

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM