Loop Over Rows & Columns of Rcpp Matrix in R (2 Examples)

 

In this post, we show you how to make a loop over the rows or columns of an Rcpp matrix in R. Rcpp is an R package which allows you to integrate C++ code directly into R, we recommend you to take a look at our post about it when you never worked with Rcpp before.

This post has the following structure.

So let’s start right away!

 

Example 1: With Standard Rcpp

We load the Rcpp package.

if (!require('Rcpp', quietly = TRUE)) { install.packages('Rcpp') } 
library('Rcpp') # Load package 'Rcpp'

Define a function called “fun_cpp” which takes a matrix as input and uses a loop over the matrix rows, adding the row index to each row. Important for users of R: Indices start with 0 in C++!

cppFunction(' 
Rcpp::NumericMatrix fun_cpp( Rcpp::NumericMatrix Mat ) {
 
   // You can get the number of rows and columns of matrix Mat as follows
   Rcout << "Mat.nrow(): " << Mat.nrow() << std::endl;
   Rcout << "Mat.ncol(): " << Mat.ncol() << std::endl;
   int nrow_Mat = Mat.nrow();
 
   // Conduct loop over the rows of matrix Mat
   // For each row: add the index of the row to the matrix values
   for ( int i=0; i<nrow_Mat; i++ ) {
     Mat(i, _) = Mat(i, _) + i;
   }
   return Mat;
}
')

Equivalently, we can write the same function looping over the columns of the matrix instead, called “fun_cpp2”.

cppFunction(' 
Rcpp::NumericMatrix fun_cpp2( Rcpp::NumericMatrix Mat ) {
 
   // You can get the number of rows and columns of matrix Mat as follows
   Rcout << "Mat.nrow(): " << Mat.nrow() << std::endl;
   Rcout << "Mat.ncol(): " << Mat.ncol() << std::endl;
   int ncol_Mat = Mat.ncol();
 
   // Conduct loop over the columns of matrix Mat
   // For each column: add the number of the column to the matrix values
   for ( int i=0; i<ncol_Mat; i++ ) {
     Mat(_, i) = Mat(_, i) + i;
   }
   return Mat ;
}
')

Try out both functions for an example matrix.

Mat <- matrix(1:(2*3), ncol = 2, nrow = 3)
 
Mat
#      [,1] [,2]
# [1,]    1    4
# [2,]    2    5
# [3,]    3    6
 
fun_cpp(Mat)
# Mat.nrow(): 3
# Mat.ncol(): 2
#      [,1] [,2]
# [1,]    1    4
# [2,]    3    6
# [3,]    5    8
 
fun_cpp2(Mat)
# Mat.nrow(): 3
# Mat.ncol(): 2
#      [,1] [,2]
# [1,]    1    5
# [2,]    2    6
# [3,]    3    7

 

Example 2: With RcppArmadillo

As a data scientist, a very useful additional package is RcppArmadillo. The package brings the rich linear algebra library Armadillo from C++ into R. We have written a blog post about it here. A documentation of the Armadillo functions and classes can be found here.

The equivalent function of fun_cpp() (looping over the rows) with RcppArmadillo is written as

cppFunction(depends = "RcppArmadillo", ' 
arma::mat fun_cpp_arma(arma::mat Mat) {
 
   // You can get the number of rows and columns of matrix Mat as follows
   Rcout << "Mat.n_rows: " << Mat.n_rows << std::endl;
   Rcout << "Mat.n_cols: " << Mat.n_cols << std::endl;
   int nrow_Mat = Mat.n_rows;
 
   // Conduct loop over the rows of matrix Mat
   // For each row: add the number of the row to the matrix values
   for ( int i=0; i<nrow_Mat; i++ ) {
     Mat.row(i) = Mat.row(i) + i;
   }
   return Mat ;
}
')

and the equivalent function of fun_cpp2() (looping over the columns) with RcppArmadillo is written as

cppFunction(depends = "RcppArmadillo", ' 
arma::mat fun_cpp_arma2(arma::mat Mat) {
 
   // You can get the number of rows and columns of matrix Mat as follows
   Rcout << "Mat.n_rows: " << Mat.n_rows << std::endl;
   Rcout << "Mat.n_cols: " << Mat.n_cols << std::endl;
   int ncol_Mat = Mat.n_cols;
 
   // Conduct loop over the columns of matrix Mat
   // For each column: add the number of the column to the matrix values
   for ( int i=0; i<ncol_Mat; i++ ) {
     Mat.col(i) = Mat.col(i) + i;
   }
   return Mat ;
}
')

You can see that the functions return the same output as fun_cpp() and fun_cpp2():

Mat <- matrix(1:(2*3), ncol = 2, nrow = 3)
 
Mat
#      [,1] [,2]
# [1,]    1    4
# [2,]    2    5
# [3,]    3    6
 
fun_cpp_arma(Mat)
# Mat.n_rows: 3
# Mat.n_cols: 2
#      [,1] [,2]
# [1,]    1    4
# [2,]    3    6
# [3,]    5    8
 
fun_cpp_arma2(Mat)
# Mat.n_rows: 3
# Mat.n_cols: 2
#      [,1] [,2]
# [1,]    1    5
# [2,]    2    6
# [3,]    3    7

 

Video & Further Resources

You might ask yourself: As an R user why would you bother to know how to loop through the rows of a matrix in Rcpp? Take a look at our post about the Rcpp package here. There, we show you that the integration of C++ code into R with Rcpp can significantly speed up your code.

For more information on C++, you can take a look at the following YouTube video of Klaus Iglbergers presentation about the Blaze library at the CppCon 2016, uploaded by the CppCon channel.

 

 

We have more posts on https://statisticsglobe.com/ which you might want to like into:

 

We showed you some examples of how to define Rcpp functions which loop over the rows and columns of a matrix. For comments or questions, use the section below.

 

Anna-Lena Wölwer Survey Statistician & R Programmer

This page was created in collaboration with Anna-Lena Wölwer. Have a look at Anna-Lena’s author page to get more information about her academic background and the other articles she has written for Statistics Globe.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

The maximum upload file size: 2 MB. You can upload: image. Drop file here

Top