gpt4 book ai didi

r - 查找一个向量中小于另一向量中元素的数量

转载 作者:行者123 更新时间:2023-12-03 00:11:31 25 4
gpt4 key购买 nike

假设我们有几个向量

a <- c(1, 2, 2, 4, 7)
b <- c(1, 2, 3, 5, 7)

对于 b 中的每个元素 b[i],我想找到 a 中小于 b[ 的元素数量i],或者等效的,我想知道 b_i 在 c(b[i], a) 中的排名。

我能想到一些天真的方法,例如执行以下任一 length(b) 次:

min_rank(c(b[i], a))
sum(a < b[i])

如果 length(a) = length(b) = N(其中 N 很大),最好的方法是什么?

编辑:

为了澄清,我想知道是否有一种计算效率更高的方法来做到这一点,即在这种情况下我是否可以比二次时间做得更好。

矢量化总是很酷;),谢谢@Henrik!

运行时间

a <- rpois(100000, 20)
b <- rpois(100000, 10)

system.time(
result1 <- sapply(b, function(x) sum(a < x))
)
# user system elapsed
# 71.15 0.00 71.16

sw <- proc.time()
bu <- sort(unique(b))
ab <- sort(c(a, bu))
ind <- match(bu, ab)
nbelow <- ind - 1:length(bu)
result2 <- sapply(b, function(x) nbelow[match(x, bu)])
proc.time() - sw

# user system elapsed
# 0.46 0.00 0.48

sw <- proc.time()
a1 <- sort(a)
result3 <- findInterval(b - sqrt(.Machine$double.eps), a1)
proc.time() - sw

# user system elapsed
# 0.00 0.00 0.03

identical(result1, result2) && identical(result2, result3)
# [1] TRUE

最佳答案

假设a逐渐弱排序,使用findInterval:

a <- sort(a)
## gives points less than or equal to b[i]
findInterval(b, a)
# [1] 1 3 3 4 5
## to do strictly less than, subtract a small bit from b
## uses .Machine$double.eps (the smallest distinguishable difference)
findInterval(b - sqrt(.Machine$double.eps), a)
# [1] 0 1 3 4 4

关于r - 查找一个向量中小于另一向量中元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22942710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com