【发布时间】:2015-05-06 02:27:48
【问题描述】:
我正在尝试矢量化的代码的可重现示例。
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)
【问题讨论】:
标签: r vectorization