# Calculating mean accross rows with repeated entries in R

I have this expression matrix

> head(dat[1:8,1:4])
Gene.Symbol        p1        p2         p3
1       STAT1     7.6159     7.6784     7.4430
2       STAT1     7.4435     7.2850     7.1250
3       STAT1     7.8925     7.9269     7.4956
4       STAT1     7.5867     7.9285     7.6741
5       GAPDH     8.4861     8.3189     9.0913
6       GAPDH     9.0206     8.0813     9.2360
> dim(dat)
 58324   276
>


As you are seeing, I have repeated genes, so how I take average over expression values for redundant genes finishing with one unique expression value for each gene for each sample in columns?

Using group_by from dplyr

You can use group_by function from dplyr to calculate the mean of each gene symbol in each samples:

library(dplyr)
dat %>%
group_by(Gene.Symbol) %>%
summarise_at(vars(contains("p")), funs(mean(., na.rm = TRUE)))

# A tibble: 2 x 4
Gene.Symbol    p1    p2    p3
<chr>       <dbl> <dbl> <dbl>
1 GAPDH        8.75  8.20  9.16
2 STAT1        7.63  7.70  7.43


Using data.table

Using data.table to speed up the calculation, you can do:

library(data.table)
setDT(dat)
dat[, lapply(.SD, mean), by = Gene.Symbol]

Gene.Symbol      p1     p2       p3
1:       STAT1 7.63465 7.7047 7.434425
2:       GAPDH 8.75335 8.2001 9.163650
$$$$
`