This may not be the easiest way to do this, but it gives the desired result, and since I wrote it, I thought that I could also publish it (using the data from the example by @konvas):
require(dplyr) dat %>% group_by(m = cumsum(is.na(value))) %>% summarise(n = n() -1, time = first(time[!is.na(value)])) %>% ungroup() %>% filter(n > 0 & m > 0) %>% select(-m) #Source: local data frame [2 x 2] # # n time #1 2 20 #2 3 60
Edit: I made a small correction in response to Ananda's comment, I hope that now it works better. For example, if the data was:
dat <- data.frame(time = seq(10, 90, 10), value = c(0, 2, 1, NA, NA, 30, 68, 0, NA)) dat
As a result, the code:
dat %>% group_by(m = cumsum(is.na(value))) %>% summarise(n = n() -1, time = first(time[!is.na(value)])) %>% ungroup() %>% filter(n > 0 & m > 0) %>% select(-m) #Source: local data frame [1 x 2] # # n time #1 3 60
source share