



下載本文檔
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
1、Rcpp Quick Reference GuideDirk Eddelbuettela and Romain Franoisba; bhttps:/romain.rbind.io/This version was compiled on November 5, 2018This document provides short code snippets that are helpful for using the Rcpp (Eddelbuettel et al., 2018; Eddelbuettel and Franois, 2011
2、; Eddel-buettel, 2013).Rcpp | quickref | R | C+Important NotesUsing matricesCreate simple vectorsInline C+ Compile in RExtract and set singleelements/package=RcppRcpp Vignette | November 5, 2018 | 14/ extract single values double x0 = xx0; double x1 = xx(1);double y0 = yyfoo
3、; double y1 = yybar;# Note - this is R code.# cppFunction in Rcpp allows rapid testing.require(Rcpp)cppFunction(NumericVector exfun(NumericVector x, int i) x = x*i;return x;)SEXP x; std:vector y(10);/ from SEXPNumericVector xx(x);/ of a given size (filled with 0)NumericVector xx(10);/ . with a defau
4、lt for all valuesNumericVector xx(10, 2.0);/ range constructorNumericVector xx(y.begin(), y.end();/ using createNumericVector xx = NumericVector:create(1.0, 2.0, 3.0, 4.0);NumericVector yy = NumericVector:create(Namedfoo = 1.0,_bar= 2.0);/ _ short for Named/ Initializing from SEXP,/ dimensions handl
5、ed automaticallySEXP x;NumericMatrix xx(x);/ Matrix of 4 rows & 5 columns (filled with 0)NumericMatrix xx(4, 5);/ Fill with valueint xsize = xx.nrow() * xx.ncol();for (int i = 0; i xsize; i+) xxi = 7;/ Same as above, using STL fillstd:fill(xx.begin(), xx.end(), 8);/ Assign this value to single eleme
6、nt/ (1st row, 2nd col)xx(0,1) = 4;/ Reference the second column/ Changes propagate to xx (same applies for Row)NumericMatrix:Column zzcol = xx( _, 1); zzcol = zzcol * 2;/ Copy the second column into new objectNumericVector zz1 = xx( _, 1);/ Copy submatrix (top left 3x3) into new objectNumericMatrix
7、zz2 = xx( Range(0,2), Range(0,2);/ If you experience compiler errors, please check/ that you have an appropriate version of g+./ See Rcpp-FAQ for more information./ Many of the examples here imply the following: #include using namespace Rcpp;/ The cppFunction will automatically add this./ Or, prefix
8、 Rcpp objects with the Rcpp namespace/ as e.g. in:Rcpp:NumericVector xx(10);/ set single valuesxx0 = 2.1;xx(1) = 4.2;yyfoo = 3.0;/ grow the vectoryyfoobar = 10.0;Interface with RFirst step in R.STL interfaceAdditional C+.Rcpp AttributesIn C+.On the command-line.Back in R.2 | https:/cran.r-project.or
9、g/package=RcppEddelbuettel and Franois# From shell, above package directoryR CMD build myPackageR CMD check myPackage_1.0.tar.gz # Optional R CMDTALL myPackage_1.0.tar.gz/ Add code below into C+ file Rcpp_example.cpp#include using namespace Rcpp;/ Place the Rcpp:export tag/ right above function decl
10、aration./ Rcpp:exportdouble muRcpp(NumericVector x)int n = x.size(); / Size of vectordouble sum = 0;/ Sum value/ For loop, note cpp index shift to 0for(int i = 0; i x = Rx).NumericVector xx(x);/ clone is slower and uses extra memory./ Safe. No side effects.NumericVector yy(clone(y);xx0 = yy0 = -1.5;
11、int zz = xx0;/ use wrap() to return non-SEXP objects, e.g:/ return(wrap(zz);/ Build and return a listList ret; retx = xx;rety = yy;return(ret);/ sum a vector from beginning to enddouble s = std:accumulate(x.begin(),x.end(), 0.0);/ prod of elements from beginning to endint p = std:accumulate(vec.begi
12、n(),vec.end(), 1, std:multiplies();/ inner_product to compute sum of squaresdouble s2 = std:inner_product(res.begin(),res.end(), res.begin(), 0.0);# In R, create a package shell. For details, # see the Writing R Extensions manual and # the Rcpp-package vignette.Rcpp.package.skeleton(myPackage)# Add
13、R code to pkg R/ directory. Call C+ # function. Do type-checking in R.myfunR - function(Rx, Ry) ret = .Call(myCfun, Rx, Ry,package=myPackage)return(ret)require(myPackage)aa - 1.5bb - 1.5cc - myfunR(aa, bb) aa = bb# FALSE, C+ modifies aaaa - 1:2bb - 1:2cc - myfunR(aa, bb)identical(aa, bb)# TRUE, R/C+
14、 types dont match # so a copy was madeexfun(1:5, 3)# Use evalCpp to evaluate C+ expressionsevalCpp(std:numeric_limits:max()Random Number Generation functionsIn R:.Rcpp ExtensionsRcpp sugarEnvironmentEddelbuettel and FranoisRcpp Vignette| November 5, 2018 | 3/ Obtain an R environment Environment stat
15、s(package:stats); Environment env( 2 ); / by position/ Special environments Environment:Rcpp_namespace(); Environment:base_env(); Environment:base_namespace(); Environment:global_env(); Environment:empty_env();/ Extract function from specific environmentNumericVector x =NumericVector:create(-2.0,-1.
16、0,0.0,1.0,2.0); IntegerVector y =IntegerVector:create(-2, -1, 0, 1, 2);NumericVector xx = abs( x ); IntegerVector yy = abs( y );bool b = all( x 2 ).is_true();NumericVector xx = ceil( x ); NumericVector xx = ceiling( x ); NumericVector yy = floor( y ); NumericVector yy = floor( y );NumericVector xx =
17、 exp( x ); NumericVector yy = exp( y );NumericVector xx = head( x, 2 ); IntegerVector yy = head( y, 2 );IntegerVector xx = seq_len( 10 ); IntegerVector yy = seq_along( y );/ Enable C+11/ Rcpp:plug(cpp11)/ Enable OpenMP (excludes macOS)/ Rcpp:plug(openmp)/ Use the RcppArmadillo package/ Requires diff
18、erent header file from Rcpp.h #include / Rcpp:depends(RcppArmadillo)Rcpp:sourceCpp(path/to/file/Rcpp_example.cpp) x - 1:5all.equal(muRcpp(x), mean(x) all.equal(var(x),varRcpp(x)/ Set seedRNGScope scope;/ For details see Section 6.7.1-Distribution/ functions of the Writing R Extensions manual./ome ca
19、ses (e.g. rnorm), dist-specific/ arguments can be omitted; when in doubt,/ specify all dist-specific arguments. The use/ of doublesrather than integers for dist-/ specific arguments is recommended. Unless/ explicitly specified, log=FALSE./ Equivalent to R calls NumericVector xx = runif(20); NumericV
20、ector xx1 = rnorm(20); NumericVector xx1 = rnorm(20, 0); NumericVector xx1 = rnorm(20, 0, 1);/ Example vector of quantiles NumericVector quants(5); for (int i = 0; i 5; i+) quantsi = (i-2);/ in R, dnorm(-2:2)NumericVector yy = dnorm(quants) ; NumericVector yy = dnorm(quants, 0.0, 1.0) ;/ in R, dnorm
21、(-2:2, mean=2, log=TRUE)NumericVector yy = dnorm(quants, 2.0, true) ;/ Note - cannot specify sd without mean/ in R, dnorm(-2:2, mean=0, sd=2, log=TRUE)NumericVector yy = dnorm(quants, 0.0, 2.0, true) ;/ To get original R api, use Rf_*double zz = Rf_rnorm(0, 2);NumericVector xx = rep( x, 3 ); Numeric
22、Vector xx = rep_len( x, 10 ); NumericVector xx = rep_each( x, 3 );IntegerVector yy = rev( y );double varRcpp(NumericVector x, bool bias = true)/ Calculate the mean using C+ functiondouble mean = muRcpp(x); double sum = 0;int n = x.size();for(int i = 0; i n; i+)sum += pow(xi - mean, 2.0); / Squareret
23、urn sum/(n-bias); / Return varianceCalling Functions in RModulesReferencesEddelbuettel D (2013). Seamless R and C+ Integration with Rcpp. Use R!Springer, New York. ISBN 978-1-4614-6867-7.Eddelbuettel D, Franois R (2011). “Rcpp: Seamless R and C+ Integration.”Journal of Statistical Software, 40(8), 1
24、18. URL /v40/i08/.Eddelbuettel D, Franois R, Allaire J, Ushey K, Kou Q, Russel N, Chambers J, Bates D (2018). Rcpp: Seamless R and C+ Integration. R package version 1.0.0, URL http:/CRAN.R-P/package=Rcpp.4 | /package=RcppEddelbuettel and Fran
25、ois/ Do NOT expect to have a performance gain/ when calling R functions from R!/ Retrieve functions from default loaded env.Function rnorm(rnorm);rnorm(100, _mean = 10.2, _sd = 3.2 );/ Passing in an R function and obtaining results/ Make sure function conforms with return type!NumericVector callFunc
26、tion(NumericVector x,Function f) NumericVector res = f(x);return res;/* R# The following is R code executed # by sourceCpp() as a convenience. x = 1:5callFunction(x, sum)*/ Warning - Module-based objects do not persist/ across quit(save=yes)/reload cycles. To be/ safe, save results to R objects and
27、remove/ module objects before exiting R./ To create a module-containing package from R:/ Rcpp.package.skeleton(mypackage, module=TRUE)class Bar public:Bar(double x_) : x(x_), nread(0), nwrite(0) double get_x( ) nread+;return x;void set_x( double x_) nwrite+; x = x_;IntegerVector stats() const returnInte
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 復(fù)雜系統(tǒng)中的因果涌現(xiàn)機制研究
- 草屑覆蓋對極度退化高寒草地上人工草地恢復(fù)的貢獻
- 教師書面糾正性反饋對學(xué)生學(xué)習(xí)投入和語言知識習(xí)得的影響研究
- 科技創(chuàng)新驅(qū)動的商業(yè)智能化升級
- 三種植物內(nèi)生真菌化學(xué)成分及其生物活性研究
- 智能交通系統(tǒng)中隱私保護性屬性基加密方案研究與設(shè)計
- 購房合同范本中介
- 基于骨骼點信息的機械臂示教學(xué)習(xí)及其變阻抗動作泛化研究
- 棉花腺體發(fā)育基因Gl2和Gl3的調(diào)控及低酚棉材料創(chuàng)制
- 基因檢測在災(zāi)難救援應(yīng)用行業(yè)深度調(diào)研及發(fā)展戰(zhàn)略咨詢報告
- 親子教育活動指導(dǎo)課件
- 青島啤酒企業(yè)文化
- 中華民族的形成與發(fā)展(原版)
- 雪鐵龍云逸C4說明書
- 《健美操裁判法》課件
- 2022輸變電工程建設(shè)安全管理規(guī)定
- 備課專業(yè)化讀書分享課件
- 《爆破作業(yè)單位許可證》申請表
- 人教版二年級數(shù)學(xué)下冊教材分析
- 市政道路雨、污水管道工程施工技術(shù)課件
- 全冊(教學(xué)設(shè)計)-蘇教版勞動六年級下冊
評論
0/150
提交評論