How to replace repeated measurements with the mean of the first three or two measurements in R

This is a slight variation on a question I asked previously, which I have not been able to adapt the answer for.

When there are repeated measurements I would like to replace the associated BP/BP2 with the mean for the first three measurements (if >=3), or the mean of two measurements (if == 2).

This is my data:

ID <- c(3,3,3,3,3,3,5,5,5,5)
Measurement <- c(2, 2, 2, 2, 2, 19, 6, 6, 7, 8)
BP <- c(14, 14, 15, 16, 14, 13, 14, 17, 18, 20)
BP2 <- c(7, 7, 8, 9, 10, 11, 14, 7, 8, 9)
DF1 <- data.frame(ID, Measurement, BP, BP2)

DF1

This is what I would like it to look like:

DF2

Thank you for any help!!

>Solution :

You can use head, which will automatically compute the mean on the first 3 values, or less if there are no three values:

DF1 %>% 
  group_by(ID, Measurement) %>%
  summarise(across(BP:BP2, ~ mean(head(.x, 3))))

     ID Measurement    BP   BP2
  <dbl>       <dbl> <dbl> <dbl>
1     3           2  14.3  7.33
2     3          19  13   11   
3     5           6  15.5 10.5 
4     5           7  18    8   
5     5           8  20    9   

Leave a Reply