用于子集字符串的 Rcpp 函数
Rcpp function for subsetting strings
我想知道是否有一个Rcpp
函数将Rcpp::String
数据类型作为输入并返回字符串的给定字符(按索引(。例如,提取字符串索引 0 处的字符。这等效于 c++ 中string
标头中的string::at
方法。我写过这个:
#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
类型之间进行转换。
您可以使用Rcpp::StringVector
将字符串的 R 向量直接馈送到C++。这显然也可以处理单个元素。
获取向量第 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
相关文章:
- rcpp函数中的清理时间很长
- 用于子集字符串的 Rcpp 函数
- 在模板化的 Rcpp 函数中调用另一个 cpp 函数
- Rcpp 函数在打包时使 RStudio 崩溃
- 从 Rcpp 函数返回指向"新"对象的指针的正确方法
- RCPP 函数,用于在 4 个方向上生成随机游走
- 从 Rcpp c++ 函数获取 r 函数参数
- Rcpp 函数在使用 "long" 输入时崩溃 R
- 收到Rcpp函数的结果后会话崩溃
- 将RCPP函数扩展到任何类型的输入向量
- 更改 R 包的导出模式以隐藏 Rcpp 函数
- 从 Tableau 调用 Rcpp 函数时出错.如何解释和调试 Rserve 日志
- 将 R 函数作为参数传递给 RCpp 函数
- Rcpp函数在给定值及其频率的向量的情况下找到中值
- Rcpp函数比相同的R函数慢
- 如何在Rcpp函数中声明输入
- 如果添加print语句,相同的Rcpp函数返回不同的输出
- R Studio在使用Rcpp函数后崩溃
- 无参数的Rcpp函数
- 如何改变Rcpp函数中R结构的值