【发布时间】:2015-02-23 23:51:53
【问题描述】:
来自 TRUE/FALSE 的向量
set.seed(1)
x = rnorm(1503501) > 0
我正在寻找一种高性能(快速)方法来获取n TRUE 的第一个系列中第一个 TRUE 的位置。
我正在处理的向量 (x) 正好包含 1503501 元素(除了其中一些更短的元素)。以下是我目前的解决方案。它使用 for 循环,但在 R 中 for 循环非常慢。有更好、特别快的解决方案吗?
n = 20
count = 0
solution = -1
for (i in 1:length(x)){
if (x[i]){
count = count + 1
if (count == n){solution = i+1-n; break}
} else {count = 0}
}
print(solution)
1182796
我正在考虑使用矢量化函数并执行y = which(x) 或最终y = paste(which(x)) 之类的操作,并寻找特定的模式,但我不知道该怎么做。
【问题讨论】:
-
公平的问题 (+1),但你刚刚发明了“性能”吗?
-
哈哈。好吧,我是 ESL。但是我用
performant这个词并没有完全错(见this post)
标签: r performance count boolean