I have a dataset of genes in groups and each gene has a score:
Group Gene Score
1 AQP11 0.55
1 CLNS1A 0.2
1 RSF1 0.54
2 CFDP1 0.41
2 CHST6 0.42
3 ACE 0.63
3 NOS2 0.63
I'm looking to examine the top scored gene per group, and see the average difference in score between that gene and all others in its group.
Outputting for example (just to note calculated by hand):
Group Gene Score Avg_TopGene_Difference_Per_Locus
1 AQP11 0.55 0.18 # difference of AQP11 score with the other genes: (0.35+0.01)/2
1 CLNS1A 0.2 0.18
1 RSF1 0.54 0.18
2 CFDP1 0.41 ...
2 CHST6 0.42
3 ACE 0.63
3 NOS2 0.63
I am trying to use a combination of group_by() and top_n but I'm not getting far with doing the actual difference calculation as diff() is sequential and not going back to only use my top score gene.
Input data:
structure(list(Group = c(1L, 1L, 1L, 2L, 2L, 3L, 3L), Gene = c("AQP11",
"CLNS1A", "RSF1", "CFDP1", "CHST6", "ACE", "NOS2"), Score = c(0.5566507,
0.2811747, 0.5269924, 0.4186066, 0.4295135, 0.634, 0.6345), direct_count = c(4L,
0L, 3L, 1L, 1L, 1L, 1L), secondary_count = c(5L, 2L, 6L, 2L,
3L, 1L, 1L)), row.names = c(NA, -7L), class = c("data.table",
"data.frame"))