RCPP无法从R包中导入Hessian&39;Numderiv&39;包中、Hessian、RCPP、Numderiv

2023-09-03 11:03:17 作者:败家

我正在尝试构建一个包,该包使用包‘numDeriv’中的函数‘hesian’。但是,当我构建包并运行代码时,我收到错误

无法将对象转换为环境:[type=Character;Target=ENVSXP]。

如何往eclipse中导入单个java文件

下面的简化RCPP代码示例

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
#include <stdio.h> 
#include<armadillo>
using namespace Rcpp;
using namespace std;


double testfunc(double X){

  return pow(X+1,2);

}


double hessian_rcpp(double X){

  Rcpp::Environment numDeriv("package:numDeriv");
  Rcpp::Function hessian = numDeriv["hessian"];

  Rcpp::List hessian_results = hessian(
  Rcpp::_["func"] = Rcpp::InternalFunction(testfunc), 
    Rcpp::_["x"] = X);

  arma::vec out = Rcpp::as<arma::vec>(hessian_results[0]);

  return out[0];
}

// [[Rcpp::export]]
double returnhess(double X){

  double out = hessian_rcpp(X);

  return out;

}

然后在生成包后,运行以下R代码会导致错误。

library(test)
returnhess(X=3)
Error in returnhess(X = 3) : 
Cannot convert object to an environment: [type=character; target=ENVSXP].

我的命名空间是

useDynLib(test, .registration=TRUE)
importFrom(Rcpp, evalCpp)
exportPattern("^[[:alpha:]]+")

我的描述是

Package: test
Type: Package
Title: What the Package Does (Title Case)
Version: 0.1.0
Author: Who wrote it
Maintainer: The package maintainer <yourself@somewhere.net>
Description: More about what it does (maybe more than one line) Use four spaces when indenting paragraphs within the Description.
License: What license is it under?
Imports: Rcpp, RcppArmadillo, numDeriv
LinkingTo: Rcpp, RcppArmadillo, numDeriv
Encoding: UTF-8
LazyData: true
我的R版本是3.5.1,RStudio版本是1.1.456,RCPP版本是0.12.19,RcppArmadillo版本是0.9.100.5.0,NumDeriv版本是2016.8.1。我的操作系统是Windows 10。

我使用类似的方法成功地从R包‘stats’导入了‘Optimize’。下面的简化代码示例

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
#include <stdio.h> 
#include<armadillo>
using namespace Rcpp;
using namespace std;

  double testfunc(double X){

  return pow(X+1,2);

}

double optim_rcpp(){

  Rcpp::Environment stats("package:stats");
  Rcpp::Function optimize = stats["optimize"];

  Rcpp::List opt_results = optimize(
  Rcpp::_["f"] = Rcpp::InternalFunction(testfunc), 
  Rcpp::_["lower"] = -10, 
  Rcpp::_["upper"] =  10);

  arma::vec out = Rcpp::as<arma::vec>(opt_results[0]);

  return out[0];
}

// [[Rcpp::export]]
double returnoptim(){

  double out = optim_rcpp();

  return out;

}

与上面相同的命名空间和描述

然后运行以下R代码即可工作

returnoptim()
[1] -1

推荐答案

作为一种解决办法,您可以添加

 Depends:numDeriv

到您的DESCRIPTION。这可确保numDeriv包与您的包一起加载。

顺便说一句:我不会在包中使用using namespace Rcpp;。而且我永远不会使用using namespace std;。我想不出使用#include <stdio.h>的充分理由,而当使用RcppArmadillo时,#include<armadillo>是不必要的。