c++ - Rcpp Armadillo : RStudio says "exp" is ambiguous

标签 c++ r rstudio rcpp

我正在使用以下代码在 RStudio 中尝试 Rcpp/RcppArmadillo:

#include <RcppArmadillo.h>

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

using namespace Rcpp;
using std::exp;
using std::log1p;

// [[Rcpp::export]]
arma::vec log1pexp(arma::vec x) {
  for(int ii = 0; ii < x.n_elem; ++ii){
    if(x(ii) < 18.0){
      x(ii) = log1p(exp(x(ii)));
    } else{
      x(ii) = x(ii) + exp(-x(ii));
    }
  }
  return x;
}

RStudio 表示对 exp 的调用不明确。我尝试在代码中调用 std::exp 而不是 using std::exp 但没有成功。代码通过 Rcpp::sourceCpp('filename.cpp') 进行编译,不会出现警告。如果我在代码中转换 (float)x(ii) 警告就会消失,但如果 我转换了(double)x(ii)

感谢任何见解,我对 C++ 和 RStudio 都缺乏经验。

发生情况的图片

enter image description here

最佳答案

对于初学者来说,不要这样做

using namespace Rcpp;
using std::exp;
using std::log1p;

如有疑问,请明确说明。然后你的代码就变成了

#include <RcppArmadillo.h>

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

// [[Rcpp::export]]
arma::vec log1pexp(arma::vec x) {
    for(size_t ii = 0; ii < x.n_elem; ++ii){
        if(x(ii) < 18.0){
            x(ii) = std::log1p(std::exp(x(ii)));
        } else{
            x(ii) = x(ii) + std::exp(-x(ii));
        }
    }
    return x;
}

并且编译顺利(在我还将循环的 int 更改为 size_t 之后)——并且在 RStudio IDE 中没有出现问题(使用相当新的每日,1.0.116)。

    标准库中的
  • std::exp(),使用double
  • Rcpp::exp() 来自 Rcpp Sugar,使用我们的 vector
  • arma::exp() 来自 Armadillo 使用其 vector

而且我总是发现最简单的方式是明确的。

编辑:我错过了log1p。使用 std:: 作为前缀也需要 C++11。进行了两项更改。

关于c++ - Rcpp Armadillo : RStudio says "exp" is ambiguous,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40997722/

相关文章:

c++ - 在 Win32 C++ 中创建 GUI

r - 计算可能包含 NA/缺失值的列值的组合(不是排列)

r - 是否有任何明确保证 dplyr 操作保留行顺序?

R 更新 |版本不匹配

R session 因 renv 0.17.2 卡住

c++ - 可以创建的最大线程数是多少?多线程时是否需要考虑系统配置

c++ - std::function 的问题

c++ - 基类到派生类的类型转换

r - 将 case_when 与 mutate 和函数一起使用时出错 : getting closest number to zero with NA

linux - 使用 Shell 脚本自动安装 R-Studio