Your function looks like it just subtracts the target value from the value of each cell in your array. Any negative values ββare replaced with 0. In this case, you do not need loops, you can just use the R built-in to the vector to do this:
set.seed(123)
Here are a few benchmarks showing the difference in speed when working on matrix , as opposed to working on data.frame . f.df( df ) and fm( m ) are two functions that work on data.frame and a matrix with 1 million resepctively elements:
require( microbenchmark ) microbenchmark( f.df( df ) , fm( m ) , times = 10L )
Work on the matrix is ββtwo orders of magnitude faster when the matrix is ββlarge.
If you really need to use the apply function, you can aplpy ββfor each matrix cell as follows:
m <- matrix( runif(25) , nrow = 5 ) target <- 0.5 apply( m , 1:2 , function(x) max(x - target , 0 ) )
Simon O'Hanlon
source share