KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I made a first stab at an Rcpp function via inline and it solved my speed problem (thanks Dirk!): Replace negative values by zero The initial version looked like this: library(inline) cpp_if_src <- ' Rcpp::NumericVector xa(a); int n_xa = xa.size(); for(int i=0; i < n_xa; i++) { if(xa[i]<0) xa[i] = 0; } return xa; ' cpp_if <- cxxfunction(signature(a="numeric"), cpp_if_src, plugin="Rcpp") But when called cpp_if(p) , it overwrote p with the output, which was not as intended. So I assumed it was passing by reference. So I fixed it with the following version: library(inline) cpp_if_src <- ' Rcpp::NumericVector xa(a); int n_xa = xa.size(); Rcpp::NumericVector xr(a); for(int i=0; i < n_xa; i++) { if(xr[i]<0) xr[i] = 0; } return xr; ' cpp_if <- cxxfunction(signature(a="numeric"), cpp_if_src, plugin="Rcpp") Which seemed to work. But now the original version doesn't overwrite its input anymore when I re-load it into R (i.e. the same exact code now doesn't overwrite its input): > cpp_if_src <- ' + Rcpp::NumericVector xa(a); + int n_xa = xa.size(); + for(int i=0; i < n_xa; i++) { + if(xa[i]<0) xa[i] = 0; + } + return xa; + ' > cpp_if <- cxxfunction(signature(a="numeric"), cpp_if_src, plugin="Rcpp") > > p [1] -5 -4 -3 -2 -1 0 1 2 3 4 5 > cpp_if(p) [1] 0 0 0 0 0 0 1 2 3 4 5 > p [1] -5 -4 -3 -2 -1 0 1 2 3 4 5 I'm not the only one who has tried to replicate this behavior and found inconsistent results: https://chat.stackoverflow.com/transcript/message/4357344#4357344</
Tags (comma-separated)
Save Edits
Cancel