Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I take pairwise parallel maximum between two vectors?

Tags:

r

max

Suppose I have two vectors in R, defined as follows.

a = c(3,3,5) b = c(2,4,6) 

Is there a function that will give me the pairwise maximum between the elements of a and the elements of b, which can be run inside a formula?

I tried to do, max(a, b) but it does not get the desired output.

Desired Output:

C(3,4,6) 

Actual output:

6 
like image 513
merlin2011 Avatar asked Nov 15 '13 06:11

merlin2011


People also ask

How do you find the maximum of two vectors?

1 Answer. You can use the pmin() function to find the pairwise minimum value in two vectors. To find the pairwise maximum, you can use the pmax() function.

What is pairwise maximum?

The pairwise maximum refer to the values that are largest between the vectors.


1 Answers

Pairwise maximum, pmax(a, b), will give c(3,4,6).

a <- c(3,3,5,NA,1) b <- c(2,4,6,0,NA)  pmax(a, b) # [1]  3  4  6 NA NA  pmax(a, b, na.rm = TRUE) # [1] 3 4 6 0 1 

There is also a pairwise minimum

pmin(a, b) # [1]  2  3  5 NA NA  pmin(a, b, na.rm = TRUE) # [1] 2 3 5 0 1 

And a pairwise sum, which I pulled from this question/answer has been very useful to me at times:

psum(a, b) # == a + b # [1]  5  7 11 NA NA  psum(a, b, na.rm = TRUE) # [1]  5  7 11  0  1  psum(c(-1, NA, 4), c(0, NA, NA)) # [1] -1 NA NA  psum(c(-1, NA, 4), c(0, NA, NA), na.rm = TRUE) # [1] -1 NA  4  psum <- function(..., na.rm = FALSE) {   dat <- do.call(cbind, list(...))   res <- rowSums(dat, na.rm = na.rm)    idx_na <- !rowSums(!is.na(dat))   res[idx_na] <- NA   res  } 
like image 144
rawr Avatar answered Oct 06 '22 08:10

rawr