I have a data.frame containing items that are either repeated (r) or not repeated (nr). For each item, I would like to calculate the number of rows that intervene between that item and its immediately preceding occurrence.
The result should be that in column 'distance' below:
word <- c ('a', 'b', 'c', 'b', 'd', 'e', 'e', 'f', 'b')
repeated <- c('nr', 'r', 'nr', 'r', 'nr', 'r', 'r', 'nr', 'r')
ds <- as.data.frame(cbind(word, repeated))
ds$distance <- c(NA, NA, NA, 2, NA, NA, 1, NA, 5)
Does anyone know how to solve this? Thank you so much for your help and time!