Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C+ function that is callable from R using the Rcpp interface, that count

ID: 3918667 • Letter: W

Question

Write a C+ function that is callable from R using the Rcpp interface, that counts the number of occurrences of a particular element in a vector. The function should take two inputs from R - a vector r of length 2 1 and a value y. The function should search over the vector r and count the number of occurrences of y within r. It should handle inputs of type integer, numeric, character and logical. The input of any other type should result in an error message stating that the type specified is not supported. Name the function count Rcpp,

Explanation / Answer

#include <Rcpp.h>

// [[Rcpp::export]]

Rcpp::NumericMatrix unique_rows( Rcpp::NumericMatrix & v)

{

// Initialize a map

std::map<std::vector<double>, int> count_rows;

// Clear map

count_rows.clear();

// Count each element

for (int i = 0; i != v.nrow(); ++i) {

// Pop from R Matrix

Rcpp::NumericVector a = v.row(i);

// Convert R vector to STD vector

std::vector<double> b = Rcpp::as< std::vector<double> >(a);

// Add to map

count_rows[ b ] += 1;

}

// Make output matrix

Rcpp::NumericMatrix o(count_rows.size(), v.ncol()+1);

// Hold count iteration

unsigned int count = 0;

// Start at the 1st element and move to the last element in the map.

for( std::map<std::vector<double>,int>::iterator it = count_rows.begin();

it != count_rows.end(); ++it )

{

// Grab the key of the matrix

std::vector<double> temp_o = it->first;

// Tack on the vector, probably can be speed up.

temp_o.push_back(it->second);

// Convert from std::vector to Rcpp::NumericVector

Rcpp::NumericVector mm = Rcpp::wrap(temp_o);

// Store in a NumericMatrix

o.row(count) = mm;

count++;

}

return o;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote