Home > Software engineering >  How to maximum values of multiple vectors element wise
How to maximum values of multiple vectors element wise

Time:06-02

Hi I would like to find a maximum values for each element from multiple vectors. For example:

v1<-c(1,1,3,5,10)
v2<-c(10,2,1,1,5)
v3<-c(11,4,2,1,9)
list_of_vectors <- list(v1, v2, v3)

I would like the result to be:

vmax<-c(11,4,3,5,10)

I know that there is the pmax function, so I tried it. Because I have the vectors as a list, I did it like this:

do.call(pmax, list_of_vectors, na.rm=TRUE)

But there is an error with the solution. How can I solve this?

CodePudding user response:

Assuming the vectors are always the same length and are in a list as individual elements, then

matrixStats::colMaxs(do.call(rbind, l1))
#[1] 11  4  3  5 10

or your way,

do.call(pmax, c(l1, na.rm=TRUE))
#[1] 11  4  3  5 10

where

dput(l1)
list(c(1, 1, 3, 5, 10), c(10, 2, 1, 1, 5), c(11, 4, 2, 1, 9))
  • Related