这是我作为 data.frame 一部分的 bool 值示例:atest <- c(FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
FALSE)
我想从每个 FALSE 返回一个从 1 开始并增加 1 直到下一个 FALSE 的数字序列。
得到的所需向量为:
[1] 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1
这是实现这一点的代码,但我确信在 R 中有一种更简单或更优雅的方法来做到这一点。我一直在努力学习如何在 R 中更有效地编写代码,而不是简单地完成工作。
result <- c()
x <- 1
for(i in 1:length(atest)){
if(atest[i] == FALSE){
result[i] <- 1
x <- 1
}
if(atest[i] != FALSE){
x <- x+1
result[i] <- x
}
}
最佳答案
这是一种方法,使用方便的(但不是广为人知/使用的)基本函数:
> sequence(tabulate(cumsum(!atest)))
[1] 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1
分解:
> # return/repeat integer for each FALSE
> cumsum(!atest)
[1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3
> # count the number of occurrences of each integer
> tabulate(cumsum(!atest))
[1] 10 10 1
> # create concatenated seq_len for each integer
> sequence(tabulate(cumsum(!atest)))
[1] 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1
关于r - 更优雅的方式来返回基于 bool 值的数字序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17820752/