RCPP无法从R包中导入Hessian&39;Numderiv&39; [英] Rcpp trouble importing 'hessian' from R package 'numDeriv'
本文介绍了RCPP无法从R包中导入Hessian&39;Numderiv&39;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试构建一个包,该包使用包‘numDeriv’中的函数‘hesian’。但是,当我构建包并运行代码时,我收到错误
无法将对象转换为环境:[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
推荐答案
作为一种解决办法,您可以添加
Depends:numDeriv
到您的DESCRIPTION
。这可确保numDeriv
包与您的包一起加载。
using namespace Rcpp;
。而且我永远不会使用using namespace std;
。我想不出使用#include <stdio.h>
的充分理由,而当使用RcppArmadillo
时,#include<armadillo>
是不必要的。
这篇关于RCPP无法从R包中导入Hessian&39;Numderiv&39;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文