如何求两个向量之间的成对最大值呢?

时间:2022-04-29 21:13:40

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

假设R中有两个向量,定义如下。

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?

是否有一个函数可以给出a的元素和b的元素之间的成对最大值,它可以在公式中运行?

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

我尝试去做,max(a,b)但是它没有得到期望的输出。

Desired Output:

期望的输出:

(3,4,6)

Actual output:

实际输出:

6

1 个解决方案

#1


29  

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

两两最大,pmax(a, b)会得到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 
}

#1


29  

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

两两最大,pmax(a, b)会得到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 
}