将R循环代码转换为Rcpp:新手请求可运行示例(向量输入输出)
Hey there! Since you're just starting out with Rcpp and C++, I’ve put together a fully runnable, easy-to-follow conversion of your R code, with explanations to help you grasp the C++ side of things.
What Your Original R Code Does First
Let’s recap the logic we’re replicating:
- Iterate through every element in the
valuevector - When an element is less than -1, append five 1s to the result
- For all other elements, append a single 0
- Stop once the result vector matches the length of
value
Equivalent Rcpp Code
Here’s the C++ code that mirrors your R behavior, with comments to walk you through each step:
#include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] NumericVector generate_result(NumericVector value) { // Initialize empty vector for our final result NumericVector result; // Store the target length we need to reach int target_length = value.size(); // Loop through each element in the input vector for (int i = 0; i < value.size(); ++i) { double current_val = value[i]; if (current_val < -1) { // Add five 1s, but stop early if we hit the target length for (int j = 0; j < 5; ++j) { if (result.size() >= target_length) break; result.push_back(1.0); } } else { // Only add a 0 if we haven't reached the target length yet if (result.size() < target_length) { result.push_back(0.0); } } // Exit the main loop early once we're done building the result if (result.size() >= target_length) break; } return result; }
How to Run This in R
- Save the code above into a file named
result_generator.cpp - In your R session, run this to compile and export the C++ function:
Rcpp::sourceCpp("result_generator.cpp") - Test it with your original
valuevector:value <- c(0.2,0.3,0.4,0.5,0.6,-2.0,0.7,0.4,-10,0.1,0.2,0.4,3.0,0.6,0.7,0.8,-1.2,0.6,0.7,0.8,0.3,0.5,2,0.1,0.2) res_rcpp <- generate_result(value) str(res_rcpp)
Expected Output
You’ll get exactly the same result as your original R code:
num [1:25] 0 0 0 0 0 1 1 1 1 1 ...
Quick Learning Note
In C++, using push_back is far more efficient than R’s c(res, ...) (which creates a brand new vector every time you append). This Rcpp version won’t just match your R code’s behavior—it’ll also run faster, especially for larger datasets.
内容的提问来源于stack exchange,提问作者Andrew Bannerman

