Rcpp officially added rowSum
support to 0.12.8 . Therefore, there is no need to use the rowSumsC
function developed by Hadley in Advanced R.
Having said that, there are several problems with the code.
Rcpp currently does not support Matrix
calculations to Vector
or Matrix
to Matrix
. (Support for a later version may be added in # 583 , although RcppArmadillo
or RcppEigen
should be considered if necessary). Therefore, the following line is problematic:
w = w / rowSums(w)
To fix this, first compute rowSums
and then standardize the matrix using the traditional for
loop. Note: The C ++ loop is very different from R.
NumericVector summed_by_row = rowSums(w); for (int i = 0; i < k; ++i) { w(_,i) = w(_,i) / summed_by_row[i]; }
Next, C ++ indices start at 0
not 1
. Therefore, for the loop, there is the following:
for (int i=1; i<k; ++i)
Correction:
for (int i=0; i<k; ++i)
Finally, function parameters can be reduced, as some of the values ββare not relevant or overridden.
Function declaration comes from:
NumericMatrix Expcpp(NumericVector x, NumericMatrix w, NumericVector mu, NumericVector var, NumericVector prob, int k)
To:
NumericMatrix Expcpp(NumericVector x, NumericVector mu, NumericVector var, NumericVector prob) { int n = x.size(); int k = mu.size(); NumericMatrix w = no_init(n,k); .....
Combining all the above feedbacks, we get the desired function.
Rcpp::cppFunction( 'NumericMatrix Expcpp(NumericVector x, NumericVector mu, NumericVector var, NumericVector prob) { int n = x.size(); int k = mu.size(); NumericMatrix w = no_init(n,k); for (int i = 0; i < k; ++i) { // C++ indices start at 0 w(_,i) = prob[i] * dnorm(x, mu[i], sqrt(var[i])); } Rcpp::Rcout << "Before: " << std::endl << w << std::endl; NumericVector summed_by_row = rowSums(w); Rcpp::Rcout << "rowSum: " << summed_by_row << std::endl; // normalize by column to mimic R for (int i = 0; i < k; ++i) { w(_,i) = w(_,i) / summed_by_row[i]; } Rcpp::Rcout << "After: " << std::endl << w << std::endl; return w; }') set.seed(51231) # Test values n <- 2 x <- seq_len(n) mu <- x var <- x prob <- runif(n) mat <- Expcpp(x, mu, var, prob)
Exit
Before: 0.0470993 0.125384 0.0285671 0.160996 rowSum: 0.172483 0.189563 After: 0.273066 0.661436 0.165623 0.849300