RCPP从R包'numDeriv'导入'hessian'时遇到麻烦

时间:2018-11-09 17:43:59

标签: r rcpp

我正在尝试构建一个使用软件包“ numDeriv”中的函数“ hessian”的软件包。但是,当我生成软件包并运行代码时,出现错误

  

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

下面的示例简化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

1 个答案:

答案 0 :(得分:3)

作为解决方法,您可以添加

 Depends:numDeriv

您的DESCRIPTION。这样可以确保numDeriv软件包与您的软件包一起加载。

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