Rcpp和RcppArmadillo創(chuàng)建R語言包的實現(xiàn)方式
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的數據結構,在其之前需指明arma::。
func()函數將可以直接在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
相關文章
解決R語言報錯:Error?in?y?+?1:non-numeric?argument?to?binary
R語言編程中的常見錯誤有一些錯誤是R的初學者和經驗豐富的R程序員都可能常犯的,下面這篇文章主要給大家介紹了關于解決R語言報錯:Error?in?y?+?1:non-numeric?argument?to?binary?operator的相關資料,需要的朋友可以參考下2022-11-11
R包制作后出現(xiàn)not available for錯誤問題解決解決
這篇文章主要為大家介紹了R包制作后出現(xiàn)not available for...錯誤的問題解決方式,有需要的朋友,可以借鑒參考下,希望能夠有所幫助2021-11-11

