c++ - 用于子集字符串的 Rcpp 函数
问题描述
我想知道是否有一个Rcpp
函数将Rcpp::String
数据类型作为输入并返回字符串的给定字符(按索引)。例如,提取字符串索引 0 处的字符。这将等效于 c++ 中标头中的string::at
方法。string
我写了这个:
#include <vector>
#include <string>
#include <Rcpp.h>
using namespace Rcpp;
typedef std::vector<std::string> stringList;
int SplitGenotypesA(std::string s) {
char a = s.at(0);
int b = a - '0';
return b;
}
但宁愿不必在Rcpp::String
和std::string
类型之间进行转换。
解决方案
您可以使用 . 将字符串的 R 向量直接提供给 C++ Rcpp::StringVector
。这显然也将处理单个元素。
获取向量的第 i 个元素的第 n 个字符就像vector[i][n]
.
所以,不使用std::string
你可以这样做:
#include<Rcpp.h>
// [[Rcpp::export]]
Rcpp::NumericVector SplitGenotypesA(Rcpp::StringVector R_character_vector)
{
int number_of_strings = R_character_vector.size();
Rcpp::NumericVector result(number_of_strings);
for(int i = 0; i < number_of_strings; ++i)
{
char a = R_character_vector[i][0];
result[i] = a - '0';
}
return result;
}
现在在 R 中你可以这样做:
SplitGenotypesA("9C")
# [1] 9
或者更好,
SplitGenotypesA(c("1A", "2B", "9C"))
# [1] 1 2 9
这甚至比做同样事情的本机 R 方法快一点:
microbenchmark::microbenchmark(
R_method = as.numeric(substr(c("1A", "2B", "9C"), 1, 1)),
Rcpp_method = SplitGenotypesA(c("1A", "2B", "9C")),
times = 1000)
# Unit: microseconds
# expr min lq mean median uq max neval
# R_method 3.422 3.765 4.076722 4.107 4.108 46.881 1000
# Rcpp_method 3.080 3.423 3.718779 3.765 3.765 32.509 1000
推荐阅读
- python - 如何从线条的图案中找到真正的线条。根据绘制的图案线找到一条线的真实 x 数据点?
- php - 如何在 PHP 中引用数组中的数组
- python - Python:在列表列表中查找最频繁出现的任意长度组合
- python - 是否可以从已经捕获的外部代码中捕获异常?
- javascript - 如何在功能 javascript 上激活,而不仅仅是在功能上
- javascript - 在 URL 中传递 Javascript 变量
- swift - 使用第二个 AVPlayer 缓冲下一首歌曲
- javascript - Reduce it array to an easier way to map
- javascript - 如何使用 Jquery 总结总收入和总间接收入
- python - 如何根据字符串长度将一列拆分为多列?