Rcpp实用手册

1.数据类型介绍

C++对应于R的数据类型有如下这些:
double⇔numeric
int⇔integer
String⇔character
logical⇔bool

在C++中可以直接使用R的对象有:`

  • 向量:NumericVectorIntegerVectorCharacterVector
  • 矩阵:NumericMatrixIntegerMatrixCharacterMatrix
  • 数据框:DataFrame
  • 列表:List
  • 函数:Function
  • 其他类型:Environment,ComplexVector,RawVector,DottedPair,Language,Promise,Symbol,WeakReference

2.语法糖

算术和逻辑运算符

所有算术逻辑运算符都是可以向量化的:+,-,*,/,pow,<,<=,>,>=,==,!=,!

#include <Rcpp.h>
using namespace Rcpp;

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

其他有用的函数

  • 数学函数: abs(), acos(), asin(), atan(), beta(), ceil(), ceiling(), choose(), cos(), cosh(), digamma(), exp(), expm1(), factorial(), floor(), gamma(), lbeta(), lchoose(), lfactorial(), lgamma(), log(), log10(), log1p(), pentagamma(), psigamma(), round(), signif(), sin(), sinh(), sqrt(), tan(), tanh(), tetragamma(), trigamma(), trunc().

  • 汇总函数: mean(), min(), max(), sum(), sd(), and (for vectors) var()

  • 返回向量的汇总函数: cumsum(), diff(), pmin(), and pmax()

  • 查找函数: match(), self_match(), which_max(), which_min()

  • 重复值处理函数: duplicated(), unique()

所有标准分布的 d/q/p/r 函数
以及 noNA(x) 判断向量x不包含任何缺失值,并允许一些数学运算上的优化。

STL

这是C++所拥有的模板库,用过C++的应该都知道,具体可以到这里看boost(http://www.boost.org/doc)

迭代器

我们可以使用迭代器来操纵R的对象。

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double sum3(NumericVector x) {  //该函数实现了对x的求和
  double total = 0; 

  NumericVector::iterator it;
  for(it = x.begin(); it != x.end(); ++it) {
    total += *it;
  }
  return total;
}

要注意每个数据结构类型都有一个迭代器,
比如NumericVector::iteratorCharacterVector::iterator是不同的。

数据结构

STL所提供的数据结构也是可以使用的,Rcpp知道如何将STL的数据结构转换成R的数据结构,所以可以从函数中直接返回他们,而不需要自己进行转换。
这些数据结构有:array, bitset, list, forward_list, map, multimap, multiset, priority_queue, queue, dequeue, set, stack, unordered_map, unordered_set, unordered_multimap, unordered_multiset, vector.

具体的使用方法可以参考:http://www.cplusplus.com/reference/stl/

本文参考文献:http://adv-r.had.co.nz/Rcpp.html

作为分享主义者(sharism),本人所有互联网发布的图文均遵从CC版权,转载请保留作者信息并注明作者a358463121专栏:http://blog.csdn.net/a358463121,如果涉及源代码请注明GitHub地址:https://github.com/358463121/。商业使用请联系作者。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值