1. 預先準備
Windows下需要安裝Rtools,R中裝好Rcpp和RcppArmadillo。創(chuàng)建C++源文件func.cpp,自定義頭文件test_h.h。
源文件示例func.cpp
// [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::plugins(cpp11)]] #include <RcppArmadillo.h> #include <vector> #include "./test_h.h" using namespace Rcpp; using namespace std; // using namespace arma; // [[Rcpp::export]] RObject func(){ arma::cube A(3,4,5,arma::fill::randu); std::cout<<CONDIT<<std::endl; return wrap(A); }
// [[Rcpp::depends(RcppArmadillo)]]:用于指明需要使用RcppArmadillo。
// [[Rcpp::plugins(cpp11)]]:指明需要使用C++11。
#include "./test_h.h":表示使用第三方頭文件。第三方頭文件需要用雙引號""包括起來,并加上.h。./表示在當下文件夾(src)下搜尋文件。
// using namespace arma;不一定有用。如果要用Armadillo的數(shù)據(jù)結構,在其之前需指明arma::。
func()函數(shù)將可以直接在R中調用。
頭文件示例test_h.h
#include <iostream> #define CONDIT 1000
2. 創(chuàng)建R包步驟
新建R Package
選擇Package w/Rcpp, 并添加源文件。或者建立包以后,手動復制到src文件夾下。
R包的文件結構
修改DESCRIPTION文件
將RcppArmadillo添加進Imports和LinkingTo中。
Package: RcppPackTest 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? Encoding: UTF-8 LazyData: true Imports: Rcpp (>= 0.12.11), RcppArmadillo LinkingTo: Rcpp, RcppArmadillo
Build & Reload 建立包
3. C++11標準問題
如果要使用C++11標準,第一種方法是在Makevars文件中添加如下代碼:
CXX = g++-4.8.1 PKG_CXXFLAGS = -std=c++11
第二種方法是在.cpp文件前添加// [[Rcpp::plugins(cpp11)]]
以上就是Rcpp和RcppArmadillo創(chuàng)建R包實現(xiàn)方式的詳細內容,更多關于Rcpp和RcppArmadillo創(chuàng)建R包的資料請關注服務器之家其它相關文章!y
原文鏈接:https://blog.csdn.net/iamsuperman2/article/details/77103568