How to find pairwise maximum among multiple vectors in R?

R ProgrammingServer Side ProgrammingProgramming

The pairwise maximum refer to the values that are largest between the vectors. For example, if we have a vector that contains 1, 2, 3 and a second vector contains 2, 1, 4 then the pairwise maximum will be 2, 2, 4 because the maximum between 1 and 2 is 2, the maximum between 2 and 1 is 2, and the maximum between 3 and 4 is 4. In R, we can find these maximum values for many vectors using pmax function.

Example

> x1<-c(14,15,18,25,17,18,29)
> y1<-c(27,28,65,4,8,21,7)
> pmax(x1,y1)
 [1] 27 28 65 25 17 21 29
> x2<-sample(1:10,20,replace=TRUE)
> x2
[1] 7 8 6 10 4 8 6 6 2 2 7 2 8 8 3 7 4 9 6 7
> y2<-c(NA,sample(1:10,19,replace=TRUE))
> y2
 [1] NA 4 8 6 6 1 3 10 2 8 8 2 10 2 4 3 5 10 2 1
> pmax(x2,y2,na.rm=TRUE)
 [1] 7 8 8 10 6 8 6 10 2 8 8 2 10 8 4 7 5 10 6 7
> x3<-sample(500:575,20,replace=TRUE)
> x3
 [1] 562 541 507 556 546 544 555 511 538 537 513 513 554 552 509 505 536 529 572
[20] 525
> y3<-sample(560:575,20,replace=TRUE)
> y3
 [1] 561 567 568 571 560 575 562 570 562 569 560 565 574 567 569 560 575 573 568
[20] 574
> pmax(x3,y3)
 [1] 562 567 568 571 560 575 562 570 562 569 560 565 574 567 569 560 575 573 572
[20] 574
> x4<-rpois(20,5)
> x4
 [1] 7 6 3 6 9 3 6 6 6 6 3 6 1 4 4 10 3 4 2 3
> y4<-rpois(20,2)
> y4
 [1] 0 4 1 3 5 4 2 0 4 1 3 1 4 2 0 3 1 2 1 3
> pmax(x4,y4)
 [1] 7 6 3 6 9 4 6 6 6 6 3 6 4 4 4 10 3 4 2 3
> x5<-sample(1:10,50,replace=TRUE)
> x5
 [1] 5 6 3 6 7 9 3 8 10 7 6 10 9 4 5 6 10 3 5 9 10 3 2 4 4
[26] 3 7 10 4 4 8 6 10 6 6 1 1 6 4 7 8 7 3 9 9 1 3 10 9 10
> y5<-sample(1:5,50,replace=TRUE)
> y5
 [1] 1 4 4 3 3 5 1 4 2 5 2 1 3 2 3 4 1 3 5 5 4 3 4 1 2 2 4 4 2 1 1 1 3 3 4 2 2 2
[39] 5 1 3 3 5 1 3 2 1 5 2 5
> pmax(x5,y5)
[1] 5 6 4 6 7 9 3 8 10 7 6 10 9 4 5 6 10 3 5 9 10 3 4 4 4
[26] 3 7 10 4 4 8 6 10 6 6 2 2 6 5 7 8 7 5 9 9 2 3 10 9 10
> x6<-sample(1:100,50)
> x6
 [1] 38 24 49 14 74 79 58 12 60 66 98 48 22 50 27 34 42 81 69 55 23 73 19 78 47
[26] 21 51 96 25 62 35 53 71 6 91 40 9 77 82 26 59 36 31 76 11 4 30 89 46 95
> y6<-sample(1:100,50)
> y6
 [1] 77 40 51 54 65 85 96 18 89 47 91 44 55 2 27 33 95 58 46 97 82 14 5 56 22
[26] 38 6 98 10 43 73 69 23 86 41 64 31 99 35 21 72 29 88 37 11 16 39 84 26 87
> z6<-sample(1:100,50)
> z6
 [1] 90  3 10  4 69 26 97 32 57 24 29 74 64 45 39 100 77 36 43
[20] 20 92 48 80 55 17 98 86 81 88 51 28 76 84 9 60 23 38 63
[39] 83 89 33 85 21 42 16 59 70 87 75 35
> pmax(x6,y6,z6)
 [1] 90 40 51 54 74 85 97 32 89 66 98 74 64 50 39 100 95 81 69
[20] 97 92 73 80 78 47 98 86 98 88 62 73 76 84 86 91 64 38 99
[39] 83 89 72 85 88 76 16 59 70 89 75 95
raja
Updated on 28-Aug-2020 12:25:54

Advertisements