나는 Rcpp
과 그 기능에 아주 초보자입니다. C++ 그 자체는 말할 것도없고, 아마도 이것은 전문가들에게는 사소한 것처럼 보일 수 있습니다. 그러나 바보 같은 질문은 없습니다. 어쨌든 :C++의 NumericVector에서 여러 값을 추출하는 방법
인덱싱을 사용하여 C++에서 NumericVector의 여러 요소를 처리하는 방법이 있는지 궁금합니다.
# Initial vector
x <- 1:10
# Extract the 2nd, 5th and 8th element of the vector
x[c(2, 5, 8)]
[1] 2 5 8
이것은 내가 지금까지 내가 sourceCpp
를 사용하여 R에서 실행있어 C++ 기능에있어 무엇 : 모든 것을보다 명확하게하기 위해, 여기에 내가 할 노력하고있어의 R에 해당합니다. 그것은 효과가 있지만, 나에게는 매우 불편한 것처럼 보입니다. 내 목표를 달성하기위한 쉬운 방법이 있습니까?
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector subsetNumVec(NumericVector x, IntegerVector index) {
// Length of the index vector
int n = index.size();
// Initialize output vector
NumericVector out(n);
// Subtract 1 from index as C++ starts to count at 0
index = index - 1;
// Loop through index vector and extract values of x at the given positions
for (int i = 0; i < n; i++) {
out[i] = x[index[i]];
}
// Return output
return out;
}
/*** R
subsetNumVec(1:10, c(2, 5, 8))
*/
> subsetNumVec(1:10, c(2, 5, 8))
[1] 2 5 8