I’m looking for a neater solution than the seq_counter() function I wrote.
It seems to me that there should be something shorter and more readable in R
set.seed(1)
bool_vec <- sample(c(TRUE,FALSE), 10, replace = TRUE)
seq_counter <- function(x){
count <- rep(1,length(x))
n <- 1
for(i in 2:length(count)){
if(x[i-1]==x[i]){
count[i] <- count[i]+n
n <- n+1
}
else {
n <- 1
}
}
count
}
cbind.data.frame(bool_vec, seq_cnt=seq_counter(bool_vec))
.
bool_vec seq_cnt
1 TRUE 1
2 FALSE 1
3 TRUE 1
4 TRUE 2
5 FALSE 1
6 TRUE 1
7 TRUE 2
8 TRUE 3
9 FALSE 1
10 FALSE 2
the function simply calculates the group size, like
6 TRUE 1
7 TRUE 2
8 TRUE 3