Find the maximum and minimum value of every column and then find the maximum and minimum value of every row
Asked Answered
A

4

34

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 value of every column and the maximum and minimum value of every row.

Aftershaft answered 12/11, 2014 at 17:44 Comment(0)
A
61

Figured it out.

Minimum and maximum of every column:

apply(a,2,min)
apply(a,2,max)

Minimum and maximum of every row:

apply(a,1,min)
apply(a,1,max)

Found the information here http://www.personality-project.org/r/r.commands.html

Aftershaft answered 12/11, 2014 at 17:52 Comment(2)
how could I add na.rm = TRUE?Doublehung
apply(a,2,min, na.rm = TRUE)Doublehung
E
6

You can try

apply(a, 1, range)

Using this together with t, this gives you two columns. The first one with the minimum the second with the maximum of the rows.

head(t(apply(a, 1, range)))
         [,1]     [,2]
[1,] 95.75922 103.6956
[2,] 93.62636 106.3934
[3,] 92.70567 106.9190
[4,] 96.53577 104.4971
[5,] 96.61573 107.6691
[6,] 95.56239 105.5887

for the column maxima change 1 to 2 in the apply function.

Ecosphere answered 16/10, 2017 at 11:3 Comment(0)
G
5

See the matrixStats package. You can use colMins(), rowMaxs() and functions like this both for columns and rows.

See this answer: How to find the highest value of a column in a data frame in R?

Gyrostat answered 28/9, 2016 at 14:48 Comment(0)
I
1

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
Interbreed answered 26/7, 2018 at 16:25 Comment(1)
Apparently there is slightly faster but uglier version: do.call(pmin, lapply(seq_len(ncol(a)), function(i) a[, i]))Interbreed

© 2022 - 2024 — McMap. All rights reserved.