Search code examples
rmatrixrangemin

Calculate min() and max() of each matrix column


I'm using the following matrix:

dput(data) =

structure(c(269.643848985434, 284.856715574861, 278.687093704939, 
242.00628682971, 258.754844814539, 257.241126745939, 250.868861973286, 
267.881099879742, 266.277047023177, 264.643696397543, 283.306375294924, 
278.137760534883, 251.230201125145, 264.389782398939, 260.087893307209, 
263.933225497603, 284.947050362825, 279.185155779123, 262.722251042724, 
284.903103709221, 279.329203143716, 256.589251384139, 274.861293360591, 
270.730307921767, 233.265785723925, 249.657887518406, 247.94396802783, 
264.665669724345, 284.124271348119, 278.701742589474, 0, 0, 0
), dim = c(3L, 11L), dimnames = list(NULL, c("", "", "", "", 
"", "", "", "", "", "", "gt")))

and, for each column, I'd like to find the range of values (min and max?) and save them (f.e. in a list).

What would be an easy way to do this? Thank you!


Solution

  • The function you're looking for is range():

    range returns a vector containing the minimum and maximum of all the given arguments.

    Use apply() with MARGIN = 2 to iterate over each column, applying the range() function. Then set appropriate row names, e.g. c("min", "max"). As you want a list, use asplit() to split the columns of the resulting matrix into a list of vectors.

    Assuming your matrix is called m:

    apply(m, MARGIN = 2, range)  |>
        `rownames<-`(c("min", "max"))  |>
        asplit(MARGIN = 2)
    
    # [[1]]
    #      min      max 
    # 269.6438 284.8567 
    
    # [[2]]
    #      min      max 
    # 242.0063 258.7548 
    
    # [[3]]
    #      min      max 
    # 250.8689 267.8811 
    
    # [[4]]
    #      min      max 
    # 264.6437 283.3064 
    
    # [[5]]
    #      min      max 
    # 251.2302 264.3898 
    
    # [[6]]
    #      min      max 
    # 263.9332 284.9471 
    
    # [[7]]
    #      min      max 
    # 262.7223 284.9031 
    
    # [[8]]
    #      min      max 
    # 256.5893 274.8613 
    
    # [[9]]
    #      min      max 
    # 233.2658 249.6579 
    
    # [[10]]
    #      min      max 
    # 264.6657 284.1243 
    
    # $gt
    # min max 
    #   0   0