Count Lines Between identical Entries

Hey there,

i´ve got a data.frame looking like this:

grafik

I need a code which is able to count the lines between two identical entries. So for A it would be 6 and for B it would be 9.

Can anybody help me?

Cheers,
A346

Hi,

Something like this (see the distance column)?

library(tidyverse)

df <- tibble(letters = sample(LETTERS[1:10], 50, replace = TRUE)) %>% 
  mutate(row_id = row_number())

df %>%
  group_by(letters) %>% 
  mutate(distance = row_id - lag(row_id)) %>% 
  arrange(letters)
#> # A tibble: 50 x 3
#> # Groups:   letters [10]
#>    letters row_id distance
#>    <chr>    <int>    <int>
#>  1 A            1       NA
#>  2 A           40       39
#>  3 A           41        1
#>  4 A           43        2
#>  5 B            6       NA
#>  6 B           20       14
#>  7 B           46       26
#>  8 B           48        2
#>  9 C            3       NA
#> 10 C           18       15
#> # ... with 40 more rows

Created on 2021-02-24 by the reprex package (v1.0.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.