-2
$\begingroup$

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)
[1] 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?

$\endgroup$

1 Answer 1

3
$\begingroup$

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
```
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.