-1

I have a data frame for example:

        gene1 gene2 gene3 group
sample1   1     2     4     1
sample2   2     3     4     1
sample3   3     4     4     1
sample4   4     5     4     2
sample5   5     6     4     2

I want to calculate the average of each group, and put the result into a new data frame, like below:

group   gene1   gene2   gene3
  1       2       3      4
  2      4.5     5.5     4

How can I realize it?

Thank you very much.

Bio_farmer
  • 149
  • 1
  • 7

2 Answers2

0

Using dplyr makes it very easy to summarise all variables by group. If only some variables interest you, you can use summarise_if. Store it then in a new object.

library(dplyr) 
new_data <- data %>% group_by(group) 
                 %>% summarise_all(funs(mean)) 
tom
  • 725
  • 4
  • 17
0

As the other answer uses dplyr, I will give a solution using data.table:

library(data.table)

setDT(data)[, lapply(.SD, mean), by=.(group), .SDcols = c('gene1', 'gene2', 'gene3')]
Ankur Sinha
  • 6,473
  • 7
  • 42
  • 73