gpt4 book ai didi

c++ - 用于子集字符串的 Rcpp 函数

转载 作者:行者123 更新时间:2023-12-03 02:31:42 25 4
gpt4 key购买 nike

我想知道是否有一个 Rcpp 函数将 Rcpp::String 数据类型作为输入并返回字符串的给定字符(按索引)。例如,提取字符串索引 0 处的字符。这相当于 C++ 中 string header 中的 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::Stringstd::string 类型之间进行转换。

最佳答案

您可以使用 Rcpp::StringVector 将 R 字符串 vector 直接提供给 C++。这显然也可以处理单个元素。

获取 vector 第 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

关于c++ - 用于子集字符串的 Rcpp 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59684821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com