I have a grouped dataset that contains data that can be repeated at multiple instances within the same group. I need to count the total number of repeated values for each instance that occurs within the same group. Here is a toy set that shows my example:
structure(list(Group = c(1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3,
3), ID = c("non repeating", "repeating", "repeating", "repeating",
"repeating", "non repeating", "repeating", "repeating", "non repeating",
"repeating", "repeating", "repeating", "non repeating")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -13L))
My desired output, because I need to filter these later. would be the following:
What I’ve tried so far is the following:
ex <-
ex_data %>%
group_by(Group) %>%
mutate(
Value = case_when(
ID == lag(ID) ~
1,
TRUE ~ 0
)
) %>%
mutate(
Value = case_when(
ID == lead(ID) ~
1,
TRUE ~ Value
)
) %>%
group_by(ID, .add = T) %>%
mutate(count = sum(Value))
This produces the following, and not what I’m hoping to get as the values are being summed across each group instead of each group and ID
What am I doing wring here?