For loops in cpp. A Rcpp example
26 May 2011This blog shows a quick example of a for loop, using c++ syntax. The function loops over the inputted data and returns the results to R. The code is not the best, however it highlights how data can be taken into and taken out the c++ environment.
src<-'
//Get the R data into Rcpp format
NumericVector input(vecIn); //This is a pointer from my understanding.
//Create an integer for the size of the inputted vector
int input_n;
//Set the size of the vector to the integer
input_n = input.size();
//Create a Vector for output of the size of input.
NumericVector output(input_n);
for(int i=0;i<input_n;i++){
output(i) = input(i)/2;
}
//The wrap function is a lazy method to get the results back to R.
return wrap(output);
'
simpleForloop <- cxxfunction(signature(vecIn ="numeirc"),src,plugin="Rcpp")
simpleForloop(c(1,2,3))
In R a for loop is easy to write;
x <- c(1, 2, 3)
for(i in 1:length(x)){
print(x[i])
}
## [1] 1
## [1] 2
## [1] 3
This loop assigns i as 1 and loops through from 1 to the length of x. In c++ this is formatted differently. One must declare the object (int i=0), The indexing of objects in c++ starts at 0 unlike R. The condition to stop the loop (i<x.size()) must be provided, and set the increment by which i increase (i++). i++ is a fast and easy way to write i=i+1, and is often used in c++ code. The c++ version of the aove for loop becomes;
for ( int i = 0; i < x.size(); i++){
}