We want to set all values in an array zero that are negative.
I tried out a a lot of stuff but did not yet achieve a working solution.
I thought about a for loop with condition, however this seems not to work.
#pred_precipitation is our array
pred_precipitation <-rnorm(25,2,4)
for (i in nrow(pred_precipitation))
{
if (pred_precipitation[i]<0) {pred_precipitation[i] = 0}
else{pred_precipitation[i] = pred_precipitation[i]}
}
Thanks for the reproducible example. This is pretty basic R stuff. You can assign to selected elements of a vector (note an array has dimensions, and what you’ve given is a vector not an array):
Benchmark wars!
@James has found an even faster method and left it in a comment. I upvoted him, if only because I know his victory will be short-lived.
First, I try compiling, but that doesn’t seem to help anyone:
But wait! Dirk wrote this Rcpp thing. Can a complete C++ incompetent read his JSS paper, adapt his example, and write the fastest function of them all? Stay tuned, dear listeners.
That’s affirmative, captain.
This modifies the input
peven if you don’t assign to it. If you want to avoid that behavior, you have to clone:Which unfortunately kills the speed advantage.