MilloMarinE
MilloMarinE

Reputation: 132

Extract the minimum matrix of a set of matrix inside a list in r

I have a list with N matrix in R:

mylist <- list(a=matrix(rnorm(1:10), ncol=2), b=matrix(rnorm(1:10), ncol=2), c=matrix(rnorm(1:10), ncol=2))

I would like to extract a matrix with the minimum values in each (i,j) for the three matrix (in my real example all matrix have the same dimensions).

I can do it manually with pmin(a,b,c), but it would be impractical for my case, because I have several matrix in the list.

I tried with

lapply(mylist, function(x) pmin(x))  

but I get the original list. Any suggestions?

Thank you. Cheers.

Upvotes: 1

Views: 59

Answers (2)

tk3
tk3

Reputation: 998

Try this solution:

am <- matrix(rnorm(1:10), ncol=2)
bm <- matrix(rnorm(1:10), ncol=2)
cm <- matrix(rnorm(1:10), ncol=2)

mylist <- list(a=am, b=bm, c=cm)

working <- pmin(am, bm, cm) # What you stated is working

new <- do.call(pmin, mylist)  # Calling for all elements of a list

identical(working, new) # verify if the new answer outputs the same

Hope it helps! :)

Upvotes: 1

Jilber Urbina
Jilber Urbina

Reputation: 61214

You can use Reduce

 # creating a list of matrices
    set.seed(1)
    mylist <- list(a=matrix(rnorm(1:10), ncol=2), 
                   b=matrix(rnorm(1:10), ncol=2), 
                   c=matrix(rnorm(1:10), ncol=2))


# getting min
> Reduce("pmin", mylist)
           [,1]       [,2]
[1,] -0.6264538 -0.8204684
[2,]  0.1836433 -0.1557955
[3,] -0.8356286 -1.4707524
[4,] -2.2146999 -0.4781501
[5,]  0.3295078 -0.3053884

Upvotes: 0

Related Questions