get start and end for each factor, when there are double occurences of a factor

Viewed 38

I have a dataframe where I want to get the start and end T of a variable. Here's a subset of my dataframe:

structure(list(compID = c("d0627-Cc010-27", "d0627-Cc010-27", 
"d0627-Cc010-27", "d0627-Cc010-27", "d0627-Cc010-27", "d0627-Cc010-27", 
"d0627-Cc010-27", "d0627-Cc010-27", "d0627-Cc010-27", "d0627-Cc010-27", 
"d0627-Cc010-27", "d0627-Cc010-27", "d0627-Cc010-27", "d0627-Cc010-27", 
"d0627-Cc010-27", "d0627-Cc010-27", "d0627-Cc010-27", "d0627-Cc010-27", 
"d0627-Cc010-27", "d0627-Cc010-27"), total_turn_angle = c(NA, 
NA, NA, NA, NA, -6.45412963, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, -6.434909322, NA, NA, NA, NA), T = c(1L, 2L, 3L, 4L, 5L, 
6L, 7L, 8L, 9L, 10L, 35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 
43L, 44L)), class = "data.frame", row.names = c(NA, -20L))

I have three variables here: compID is my unique ID (I have tons of IDs and this is just one ID), total_turn_angle is the factor that I want to know the start and end T. Since I only have one value for total_turn_angle, I used the midpoint of T to put the value in. So in this example: -6.454130 is the total_turn_angle from T 1:10 and -6.434909 is the total_turn_angle for T 35:44.

Now, I want to know the start and end of T for that total_turn angle. So for this example, the answer will be:

compID          total_turn_angle    start   end
d0627-Cc010-27  -6.454130           1       10
d0627-Cc010-27  -6.434909           35      44

Hope someone could help! Thank you!

Edit: made the sample data frame smaller and edited the explanation.

1 Answers

Calling your data df:

df %>%
  group_by(
    compID
  ) %>%
  mutate(
    grp = cumsum(c(1, diff(T)) != 1)
  ) %>%
  group_by(compID, grp) %>%
  summarize(
    total_turn_angle = first(na.omit(total_turn_angle)),
    start = min(T),
    end = max(T),
    .groups = "drop"
  ) %>%
  select(-grp)
# # A tibble: 2 × 4
#   compID         total_turn_angle start   end
#   <chr>                     <dbl> <int> <int>
# 1 d0627-Cc010-27            -6.45     1    10
# 2 d0627-Cc010-27            -6.43    35    44
Related