advance-R 19.4 Rcpp sugar

在C++中,向量和矩阵的运算通常需要逐个元素进行, 或者调用相应的函数。 Rcpp通过C++的表达式模板(expression template)功能, 可以在C++中写出像R中对向量和矩阵运算那样的表达式。

R中的很多函数如sin等是向量化的, Rcpp糖也提供了这样的功能。 Rcpp糖提供了一些向量化的函数如ifelse, sapply等。

比如,两个向量相加可以直接写成x + y 而不是用循环或迭代器(iterator)逐元素计算; 若x是一个NumericVector, 用sin(x)可以返回由x每个元素的正弦值组成的NumericVector。

Rcpp糖不仅简化了程序, 还提高了运行效率。
from:http://www.math.pku.edu.cn/teachers/lidf/docs/Rbook/html/_Rbook/rcpp-sugar.html

===========================================================
Rcpp provides a lot of syntactic "sugar" to ensure that C++ functions work very similarly to their R equivalents. In fact, Rcpp sugar makes it possible to write efficient C++ code that looks almost identical to its R equivalent.
Rcpp提供了大量的语法“糖”,以确保c++函数的工作方式与对应的R函数非常相似。事实上,Rcpp sugar使编写高效的c++代码成为可能,这些代码看起来几乎与R代码相同。

  1. arithmetic and logical operators
  2. logical summary functions
  3. vector views
  4. other useful functions

arithmetic and logical operators

+, *, -, /, pow, <, <=, >, >= ,==, !=, !
use sugar to considerably simplify the implementation of pdistC().

pdistR <- function(x, ys){
  sqrt((x - ys) ^ 2)
}
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector pdistC2(double x, NumericVector ys) {
  return sqrt(pow((x - ys), 2));
}

logical summary functions

在R中, any()和all()对一个逻辑向量分别判断是否有任何真值, 以及所有元素为真值。 Rcpp糖在C++中也提供了这样的any()和all()函数。
The sugar function any() and all() are fully lazy so that any(x == 0), for example, might only need to evaluate one element of a vector, and return a special type that can be converted into a bool using .is_true(), .is_false(), or .is_na().
We could also use this sugar to write an efficient function to determine whether or not a numeric vector contains any missing values. To do this in R, we could use any(is.na(x)):

any_naR <- function(x) any(is.na(x))

However, this will do the same amount of work regardless of the location of the missing value. Here's the C++ implementation:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
bool any_naC(NumericVector x){
  return is_true(any(is_na(x)));
}
> any_naR <- function(x) any(is.na(x))
> library(microbenchmark)
> microbenchmark(
+   any_naR(x0), any_naC(x0), 
+   any_naR(x1), any_naC(x1), 
+   any_naR(x2), any_naC(x2)
+ )

Unit: microseconds
        expr     min      lq      mean   median       uq       max neval
 any_naR(x0) 382.863 467.627 678.43969 485.2620 559.2180 11793.051   100
 any_naC(x0) 319.716 325.974 416.80244 334.7915 372.6225  3362.698   100
 any_naR(x1) 384.570 467.911 725.74845 486.1165 542.7200 11709.424   100
 any_naC(x1) 320.854 325.974 370.31853 329.9560 352.9965  1200.355   100
 any_naR(x2) 249.743 329.956 387.52749 351.5735 389.1205  1426.772   100
 any_naC(x2)   1.707   2.846  28.16085   4.5520   7.3965  1530.879   100

Cpp更快

vector views

a "view" of a vector:
head(), tail(), rep_each(), rev(), seq_along(), and seq_len()
In R these would all produce copies of the vector, but in Rcpp they simply point to the existing vector and override the subsetting operator ([) to implement special behaviour. This makes them very efficient: for instance, rep_len(x, 1e6) does not have to make a million copies of x.

other useful functions

  • Math functions
  • Scalar summaries
  • Vector summaries
  • Finding values
  • Dealing with dumplicates
  • d/q/p/r for all standard distributions
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,651评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,468评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,931评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,218评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,234评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,198评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,084评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,926评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,341评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,563评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,731评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,430评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,036评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,676评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,829评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,743评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,629评论 2 354

推荐阅读更多精彩内容