Rcpp 中 if-else 语句的问题

uto*_*obi 3 c++ if-statement rcpp

使用以下简化代码,我希望从 N(0,1) 分布进行模拟,并返回一个包含模拟值的列表以及取决于模拟法线的向量(请参阅下面的代码)。问题是 if-else 语句根本不起作用!请问有人可以帮我理解问题出在哪里吗?

#include <RcppArmadillo.h>
#include <Rcpp.h>
using namespace Rcpp;

//[[Rcpp::depends(RcppArmadillo)]]

//[[Rcpp::export]]

List cond(arma::vec epsilon, IntegerVector Nsim) {
int iNsim = Nsim[0];
arma::vec ans(1);
arma::vec epsil(epsilon);
arma::vec vans  = arma::zeros(iNsim);
arma::vec vcond = arma::zeros(iNsim);
LogicalVector cond;
RNGScope scope;

for (int i=0; i<iNsim; i++) {

  ans = Rcpp::rnorm(1, 0.0, 1.0);
  vans.row(i) = ans[0];
  cond = abs(ans) >= epsil;
  if (cond) {
    vcond.row(i) = 10;
  } else {
    vcond.row(i) = -10;
  }
}

return List::create(
    _["sim"] = vans,
    _["cond"] = vcond);  
}
Run Code Online (Sandbox Code Playgroud)

我通过将其保存到 file.cpp 然后通过 sourceCpp("file.cpp") 在 R 中运行它。

Dir*_*tel 5

原始代码对于在哪里使用向量以及在哪里使用标量感到困惑。

他是更短和修复的版本:

#include <Rcpp.h>

using namespace Rcpp;

//[[Rcpp::export]]
DataFrame cond(double epsil, int iNsim) {
  double ans;
  NumericVector vans(iNsim);
  NumericVector vcond(iNsim);
  RNGScope scope;

  for (int i=0; i<iNsim; i++) {
    ans = R::rnorm(0.0, 1.0);
    vans[i] = ans;
    if (fabs(ans) >= epsil) {
      vcond[i] = 10;
    } else {
      vcond[i] = -10;
    }
  }

  return DataFrame::create(_["sim"] = vans,
                           _["cond"] = vcond);  
}
Run Code Online (Sandbox Code Playgroud)

除了在应该使用标量的地方使用(并传递)标量之外,它还纠正abs()fabs()一个常见的 C/C++ 问题。我还恢复了 Rcpp 向量 - 尽管我喜欢使用犰狳,但这里不需要它。

以下是给定随机种子的示例输出:

 R> sourceCpp("/tmp/erlis.cpp")
 R> set.seed(1)
 R> cond(1.0, 6)   
         sim cond              
 1 -0.626454  -10
 2  0.183643  -10
 3 -0.835629  -10 
 4  1.595281   10
 5  0.329508  -10
 6 -0.820468  -10
 R> 
Run Code Online (Sandbox Code Playgroud)