简体   繁体   中英

R function to find the end value of consecutive values in a boolean vector

I am trying to find the last value of a set of consecutive TRUEs in a boolean vector (is_reaching) in my dataframe which I extracted after a set of conditions as below:

transport_phase = last(rle(is_reaching)$lengths, rle(is_reaching)$lengths > 40, rle(is_reaching)$values==TRUE), transport_phase_end = cumsum(rle(is_reaching)$lengths)[transport_phase]

The above code for transport_phase gives me the correct numeric vector for the last length of consecutive TRUEs in each of my grouped variables, but when I try to find the end value of this run of TRUEs, using transport_phase_end, it just gives me the length of the vector which is the same as the transport_phase rather than the absolute value of the TRUE in this run.

I've tried other similar options from ideas on this site, but none have worked? I'm using dplyr package.

Maybe you can try this -

df <- data.frame(a = c(1:20),b = c(TRUE,FALSE,FALSE,FALSE))
tmp <- rle(df$b)
i <- max(which(tmp$lengths >= 3))
transport_phase_end <- max(cumsum(tmp$lengths[1:i]))
transport_phase_end
#[1] 20
transport_phase <- tmp$lengths[i]
transport_phase
#[1] 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM