gpt4 book ai didi

r - 向量化包含 which 语句和函数的 for 循环

转载 作者:行者123 更新时间:2023-12-04 02:43:25 24 4
gpt4 key购买 nike

我正在尝试矢量化的代码的可重现示例。

cutOffs <- seq(1,10,0.2)

plotOutput <- matrix(nrow=length(cutOffs), ncol=2)
colnames(plotOutput) <- c("x","y")
plotOutput[,"y"] <- cutOffs

for(plotPoint in 1:length(cutOffs))
{
plotOutput[plotPoint, "x"] <-
nrow(iris[ which(iris$Sepal.Length > cutOffs[plotPoint] &
iris$Sepal.Width > cutOffs[plotPoint]), ])
}

plotOutput

具体来说,我想知道的是,是否有办法对这部分进行矢量化。
nrow(iris[ which(iris$Sepal.Length > cutOffs[plotPoint] &
iris$Sepal.Width > cutOffs[plotPoint]), ])

假设我要使用 plyr 库或某种形式的应用程序,可能没有太多的加速,这正是我正在寻找的。从根本上说,我想看看是否有一些我在搜索时忽略或设法错过的矢量化技术。

更新:
Unit: milliseconds
expr min lq mean median uq max neval
op() 33663.39700 33663.39700 33663.39700 33663.39700 33663.39700 33663.39700 1
jr() 3976.53088 3976.53088 3976.53088 3976.53088 3976.53088 3976.53088 1
dd() 4253.21050 4253.21050 4253.21050 4253.21050 4253.21050 4253.21050 1
exp() 5085.45331 5085.45331 5085.45331 5085.45331 5085.45331 5085.45331 1
nic() 8719.82043 8719.82043 8719.82043 8719.82043 8719.82043 8719.82043 1
sg() 16.66177 16.66177 16.66177 16.66177 16.66177 16.66177 1

我实际在做的更现实的近似是这个
# generate data
numObs <- 1e5
iris <- data.frame( Sepal.Length = sample(1:numObs), Sepal.Width = sample(1:numObs) )

cutOffs <- 1:(numObs*0.01)

plotOutput <- matrix(nrow=length(cutOffs), ncol=2)
colnames(plotOutput) <- c("x","y")
plotOutput[,"y"] <- cutOffs

其次是人们喜欢的任何特定方法。

一般来说,它将用于具有 50,000 - 200,000 点的数据集。

使用有很大的飞跃
sum(Sepal.Length > cutOffs[plotPoint] & Sepal.Width > cutOffs[plotPoint])

这是我首先缺少的更优化方法。

然而,到目前为止,最好的答案是 sgibb 的 sg()。关键是要意识到每行中只有两个值中的最低值才是重要的。一旦进行了精神上的飞跃,就只剩下一个向量需要处理了,向量化相当简单。
# cutOff should be lower than the lowest of Sepal.Length & Sepal.Width
m <- pmin(iris$Sepal.Length, iris$Sepal.Width)

最佳答案

我想添加另一个答案:

sg <- function() {
# cutOff should be lower than the lowest of Sepal.Length & Sepal.Width
m <- pmin(iris$Sepal.Length, iris$Sepal.Width)
ms <- sort.int(m)
# use `findInterval` to find all the indices
# (equal to "how many numbers below") lower than the threshold
plotOutput[,"x"] <- length(ms)-findInterval(cutOffs, ms)
plotOutput
}

这种方法避免了 forouter循环并且比@nicola 的方法快 4 倍:
microbenchmark(sg(), nic(), dd())
#Unit: microseconds
# expr min lq mean median uq max neval
# sg() 88.726 104.5805 127.3172 123.2895 144.2690 232.441 100
# nic() 474.315 526.7780 625.0021 602.3685 706.7530 997.412 100
# dd() 669.841 736.7800 887.4873 847.7730 976.6445 2800.930 100

identical(sg(), dd())
# [1] TRUE

关于r - 向量化包含 which 语句和函数的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30054878/

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