With dplyr we can compare the adjacent elements of the Founder to create a grouping variable along with the Chromosome, and then get mean "Probabilities"
library(dplyr) library(data.table) df1 %>% group_by(Chromosome, grp1 = cumsum(Founder!=lag(Founder, default = Founder[n()]))) %>% mutate(Average = mean(Probability)) # Chromosome SNP Founder Probability grp1 Average # <int> <int> <int> <dbl> <int> <dbl> #1 1 1 7 0.6 0 0.60 #2 1 2 7 0.5 0 0.60 #3 1 3 7 0.7 0 0.60 #4 1 4 2 0.5 1 0.65 #5 1 5 2 0.8 1 0.65 #6 1 6 7 0.6 2 0.55 #7 1 7 7 0.5 2 0.55
Or using data.table , we convert "data.frame" to "data.table" ( setDT(df1) ), grouped by "Chromome" and the "Length" line identifier ( rleid ) of the Founder, we assign ( := ) mean " Probabilities "like the" Medium "column.
library(data.table) setDT(df1)[, Average := mean(Probability) , .(Chromosome, grp1 = rleid(Founder))]
source share