识别向量的第一次出现,其中 15 个值中有 12 个是 1
Identify first occurence of vector where 12 of 15 values are 1
我有一个这样的向量:
test = c(NA, 1, 1, 1, NA, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA, 1, 1, 1, 1, NA, NA, 1)
在这个向量中,我想第一次确定 15 个值中有 12 个值等于一个。
我已经开始使用 rle
来计算连续值:
#get counts of sequences
count = rle(test)
然后得到一个基于此的序列:
#make a sequence of the counts
new <- sequence(count$lengths)
然后我会将 new
中的任何值变为 0,其中 test
值等于 NA:
#when the value was na make the count 0
new[is.na(test)] <- 0
最后我会将所有其他值更改为 1:
#make all other counts 1
new[new !=0] <- 1
这将 return:
[1] 0 1 1 1 0 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 0 0 1
这就是我卡住的地方,现在我知道 15 个值中有 12 个第一次为 1 的索引位置是 idx = 6,但我卡在如何使用算法检索它。
我们可以使用 zoo::rollsum
找到下一个 15 个值总和等于或大于 12 的第一个点。
which(zoo::rollsum(test, 15, align = "left", fill = 0) >= 12)[1]
#> [1] 6
由 reprex package (v0.3.0)
于 2020-07-17 创建
我们可以用rollapply
做逻辑向量的sum
,得到和为12的第一个匹配索引match
library(zoo)
match(12, rollapply(test, width = 15, FUN = function(x) sum(x== 1, na.rm = TRUE)))
#[1] 6
我有一个这样的向量:
test = c(NA, 1, 1, 1, NA, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA, 1, 1, 1, 1, NA, NA, 1)
在这个向量中,我想第一次确定 15 个值中有 12 个值等于一个。
我已经开始使用 rle
来计算连续值:
#get counts of sequences
count = rle(test)
然后得到一个基于此的序列:
#make a sequence of the counts
new <- sequence(count$lengths)
然后我会将 new
中的任何值变为 0,其中 test
值等于 NA:
#when the value was na make the count 0
new[is.na(test)] <- 0
最后我会将所有其他值更改为 1:
#make all other counts 1
new[new !=0] <- 1
这将 return:
[1] 0 1 1 1 0 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 0 0 1
这就是我卡住的地方,现在我知道 15 个值中有 12 个第一次为 1 的索引位置是 idx = 6,但我卡在如何使用算法检索它。
我们可以使用 zoo::rollsum
找到下一个 15 个值总和等于或大于 12 的第一个点。
which(zoo::rollsum(test, 15, align = "left", fill = 0) >= 12)[1]
#> [1] 6
由 reprex package (v0.3.0)
于 2020-07-17 创建我们可以用rollapply
做逻辑向量的sum
,得到和为12的第一个匹配索引match
library(zoo)
match(12, rollapply(test, width = 15, FUN = function(x) sum(x== 1, na.rm = TRUE)))
#[1] 6