I actually like using min and max functions for things like this. In this case, we want pmax
in R.
r1[,c(1,3)] <- pmax(r1[,c(1,3)], 0)
Or a little more convoluted:
r1[,c(1,3)][r1[,c(1,3)]<0] <- 0
Benchmark
And just to satisfy the question, looks like that more convoluted way is the fastest, but replace
is pretty quick too.
library(microbenchmark)
microbenchmark(
r1[,c(1,3)] <- replace(r1[, c(1,3)], r1[, c(1,3)] < 0, 0),
r1[,c(1,3)][r1[,c(1,3)]<0] <- 0,
r1[,c(1,3)] <- pmax(r1[,c(1,3)], 0)
)
Unit: microseconds
expr min lq mean median uq max neval
r1[, c(1, 3)] <- replace(r1[, c(1, 3)], r1[, c(1, 3)] < 0, 0) 3.601 3.9005 4.97602 4.201 4.5020 25.501 100
r1[, c(1, 3)][r1[, c(1, 3)] < 0] <- 0 3.200 3.3020 4.75701 3.601 3.9020 24.201 100
r1[, c(1, 3)] <- pmax(r1[, c(1, 3)], 0) 12.601 13.1010 17.42398 13.901 15.5015 49.601 100