如何在两个向量之间取成对并行最大值? [英] How can I take pairwise parallel maximum between two vectors?
本文介绍了如何在两个向量之间取成对并行最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我在 R 中有两个向量,定义如下.
Suppose I have two vectors in R, defined as follows.
a = c(3,3,5)
b = c(2,4,6)
是否有一个函数可以给我 a
的元素和 b
的元素之间的成对最大值,它可以在公式中运行?
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?
我尝试这样做,max(a, b)
但它没有得到想要的输出.
I tried to do, max(a, b)
but it does not get the desired output.
期望的输出:
C(3,4,6)
实际输出:
6
推荐答案
Pairwise maximum, pmax(a, b)
, will give c(3,4,6)
.
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
还有一个成对最小值
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
}
这篇关于如何在两个向量之间取成对并行最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文