I\'ve got this matrix:
a <- matrix(rnorm(1000 * 18, mean = 100, sd = sqrt(10)), 1000, 18)
I would like to find the maximum and minimum v
A faster alternative for row max/min would be using pmax()
and pmin()
even though you would first have to convert the matrix to a list (data.frame is a special case of a list):
apply(a,1,min)
apply(a,1,max)
# becomes
do.call(pmin, as.data.frame(a))
do.call(pmax, as.data.frame(a))
For the columns it will be less "competitive" because of having to transpose first:
apply(a,2,min)
apply(a,2,max)
# becomes
do.call(pmin, as.data.frame(t(a)))
do.call(pmin, as.data.frame(t(a)))
Benchmarking:
a <- matrix(rnorm(1000 * 18 *10, mean = 100, sd = sqrt(10)), 1000 * 10, 18 * 10)
microbenchmark::microbenchmark(
do.call(pmin, as.data.frame(a)),
apply(a,1,min),
unit = "relative"
)
expr min lq mean median uq max neval
do.call(pmin, as.data.frame(a)) 1.000000 1.0000 1.000000 1.000000 1.000000 1.0000000 100
apply(a, 1, min) 2.281095 2.3576 2.096402 2.531092 2.618693 0.6284233 100