重复Rcpp NumericVector

问题描述 投票:0回答:1

我有一个向量

x
,我想从中创建一个由
y
的多个副本组成的向量
x
。因此,如果
x
{1, 2, 3}
并且
n
的重复次数是 3,则
y
将是
{1, 2, 3, 1, 2, 3, 1, 2, 3}
x
必须是
std::vector<double>
Rcpp::NumericVector
y
必须是
Rcpp::NumericVector
。我使用 C++20。

当然,我可以简单地迭代这些元素,例如:

const int x_size = x.size();
Rcpp::NumericVector y (x_size * n);
for(int i = 0; i < n; ++i) {
  const int s = x_size() * i;
  for(int j = 0; j < x_size; ++j) {
    y[s + j] = x[j];
  }
}

但我想有比这样的嵌套循环更好的解决方案。

我没有考虑创建

y
,而是动态地将
x
调整为
x.size() * n
大小并插入其自身的多个副本,但没有找到如何使用
Rcpp::NumericVector
来执行此操作。

那么,如何从

y
x
创建
n

c++ r rcpp
1个回答
0
投票

这已经作为 Rcpp 糖函数

rep(x, n)
存在,以等效的基本 R 函数为模型。

代码

#include <Rcpp/Rcpp>

// [[Rcpp::export]]
Rcpp::NumericVector myrep(Rcpp::NumericVector x, int n) {
    return Rcpp::rep(x, n);
}

/*** R
x <- c(1, 2, 3, 4)
n <- 3
myrep(x, n)
*/

输出

> Rcpp::sourceCpp("answer.cpp")

> x <- c(1, 2, 3, 4)

> n <- 3

> myrep(x, n)
 [1] 1 2 3 4 1 2 3 4 1 2 3 4
> 

讨论

您可能仍然想自己编写这样的函数。您有传入向量的访问器

size()
length()
,您有
n
,其余的只是两个小心的循环(以最简单的方法)。

© www.soinside.com 2019 - 2024. All rights reserved.