The name says it.
my vector
TF <- c(F,T,T,T,F,F,T,T,F,T,F,T,T,T,T,T,T,T,F)
my desired result
[1] 0 1 2 3 0 0 1 2 0 1 0 1 2 3 4 5 6 7 0
#with(rle(TF), sequence(lengths) * rep(values, lengths)) with(rle(TF), sequence(lengths) * TF) #Like Rich suggested in comments # [1] 0 1 2 3 0 0 1 2 0 1 0 1 2 3 4 5 6 7 0
You can use rle()with sequence().
rle()
sequence()
replace(TF, TF, sequence(with(rle(TF), lengths[values]))) # [1] 0 1 2 3 0 0 1 2 0 1 0 1 2 3 4 5 6 7 0
replace() coercion works for us.
replace()
You can also use inverse.seqlefrom cgwtools:
inverse.seqle
cgwtools
library(cgwtools) SEQ = inverse.seqle(rle(TF)) SEQ[!TF] = 0
Or similar to @db answer:
inverse.seqle(rle(TF))*TF # [1] 0 1 2 3 0 0 1 2 0 1 0 1 2 3 4 5 6 7 0
We can use rleid
rleid
library(data.table) ave(TF, rleid(TF), FUN = seq_along)*TF #[1] 0 1 2 3 0 0 1 2 0 1 0 1 2 3 4 5 6 7 0
Using the base R
ave(cumsum(TF==FALSE), cumsum(TF==FALSE), FUN=seq_along)-1 [1] 0 1 2 3 0 0 1 2 0 1 0 1 2 3 4 5 6 7 0
Source: https://habr.com/ru/post/1686581/More articles:Select specific properties from the entities included in the kernel - entity-framework-coreProblems with airflow scheduler as a daemon process - pythonHow to select many-to-many simulated properties in EFCore with a single SQL query - c #NodeJs util.promisify не является функцией - javascriptthis.router.navigate in Guard blocks routes in the future - angularHow to run the airflow scheduler as a daemon process? - schedulerHow to implement equals / hashCode methods for classes that contain double fields - javaTypeScript errors when using Redux-Form with React-Redux connection - reactjsIs it possible to have multiple GETs that differ only in the parameters in ASP.NET Core? - c #Entity Framework Core generates two select queries for a one-to-many relationship - entity-framework-coreAll Articles