This document demonstrates how to extract maximum values for each row in a sparse matrix using RcppArmadillo for speed and efficiency.
library(Matrix)
library(Rcpp)
library(RcppArmadillo)
library(magrittr)
A sample sparse matrix implemented in the Matrix pacakge.
<- c(1,3:8)
i <- c(2,9,6:10)
j <- 7 * (1:7)
x <- sparseMatrix(i, j, x = x) sparse_matrix
Using Inline Functions
# locate maximum value
<- Rcpp::cppFunction(
rowwise_max "arma::sp_mat sp_row_max(arma::sp_mat X) {
return arma::max(X, 1);
}", depends= "RcppArmadillo"
)
# locate position of maximum value
<- Rcpp::cppFunction(
rowwise_max_idx "arma::urowvec sp_row_max_id(arma::sp_mat X) {
return arma::index_max(X.t(), 0);
}", depends= "RcppArmadillo"
)
rowwise_max(sparse_matrix) %>% as.vector()
rowwise_max_idx(sparse_matrix) %>% as.vector()
Sourcing a .cpp File
rowwise_max.cpp
# include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
// [[Rcpp::export]]
arma::urowvec rowwise_max(arma::sp_mat X) {return arma::index_max(X, 1);
}// [[Rcpp::export]]
arma::sp_mat rowwise_max_idx(arma::sp_mat X) {return arma::max(X.t(), 0);
}
source("rowwise_max.cpp")
rowwise_max(sparse_matrix) %>% as.vector()
rowwise_max_idx(sparse_matrix) %>% as.vector()