rcpp - 第一次尝试在 Rcpp 中使用 R 函数时出错
问题描述
试图在 Rcpp 中编译一个函数,该函数会引入一个名为 read_excel 的 R 包。
不确定错误是什么意思,但也许它无法在包中找到函数?
cppFunction('IntegerVector readYear(CharacterVector filePath ) {
IntegerVector Year(filePath.size());
int n=filePath.size();
Environment pkg = Environment::namespace_env("readxl");
Function read_excel=pkg["read_excel"];
for( int i =0 ; i<n; i++){
Year[i] = read_excel(Named("path") = filePath[i],
_["range"] = "B3:B3",
_["col_names"] = false );
}
return Year;
}')
错误信息:
file391220cd2e2.cpp: In function ‘Rcpp::IntegerVector readYear(Rcpp::CharacterVector)’:
file391220cd2e2.cpp:18:22: error: invalid conversion from ‘SEXP {aka SEXPREC*}’ to ‘Rcpp::traits::storage_type<13>::type {aka int}’ [-fpermissive]
Year[i] = read_excel(Named("path") = filePath[i],
^
make: *** [file391220cd2e2.o] Error 1
g++ -std=gnu++11 -I"/opt/R/3.6.0/lib/R/include" -DNDEBUG -I"/home/rstudio-user/R/x86_64-pc-linux-gnu-library/3.6/Rcpp/include" -I"/tmp/RtmpbaxzNs/sourceCpp-x86_64-pc-linux-gnu-1.0.2" -I/usr/local/include -fpic -g -O2 -c file391220cd2e2.cpp -o file391220cd2e2.o
/opt/R/3.6.0/lib/R/etc/Makeconf:176: recipe for target 'file391220cd2e2.o' failed
Error in sourceCpp(code = code, env = env, rebuild = rebuild, cacheDir = cacheDir, :
Error 1 occurred building shared library.
解决方案
错误消息意味着不能直接将 R 函数 ( ) 的返回类型转换为 ( )SEXP
的存储类型。您可以指示这样做使用:IntegerVector
int
Rcpp
Rcpp::as<int>(...)
Rcpp::cppFunction('IntegerVector readYear(CharacterVector filePath ) {
int n = filePath.size();
IntegerVector Year(n);
Environment pkg = Environment::namespace_env("readxl");
Function read_excel=pkg["read_excel"];
for(int i =0; i<n; ++i){
Year[i] = Rcpp::as<int>(read_excel(_("path") = filePath[i],
_["range"] = "B3:B3",
_["col_names"] = false ));
}
return Year;
}')
顺便说一句,我希望在 C++ 中这样做是有充分理由的,因为它的功能将比等效的 R 函数慢,因为从 C++ 调用 R 函数是有代价的。
推荐阅读
- aws-lambda - 使用相同的 Quarkus 代码库处理 AWS HTTP 和 SQS 事件
- c# - 使用 C# 和 .NET Core 在 AWS Cognito 用户池中进行用户管理
- azure-data-explorer - 如何在 Kusto 查询上应用 python for 循环?
- javascript - 如何在javascript中的d3.js中获取拖动事件?
- python - Keras: ValueError: Input 0 of layer sequential_1 is incompatible with the layer: expected ndim=3, found ndim=2
- postgresql - psql:在一行代码中重置和重新创建数据库
- php - 将流量从特定文件夹重新路由到 PHP 脚本
- react-native - React 本机视频不使用 exoplayer 播放音频
- python - BeautifulSoup 在网页上找不到表格
- android - Android Get Default Animator Duration Scale(开发者选项)