How to flatten a matrix in R
If you have a matrix or data frame where some of the rows have values that need to be averaged. There are a few ways to go about this.
Imagine you have a table of gene expression values measured under various conditions. Each row of the table represents a gene, some of the rows represent replicate measurements of that gene. The gene name is found in the column "sys_id". Each column represents a different condition. To average the replicates you could do the following:
Example 1:
library(stats) mat <- aggregate(dat[, 2:5], list(dat$sys_id), mean)
Example 2: Create a factor with the column of gene names, then use that factor to apply a function to the values in each individual column, then recombine the columns into a dataframe or matrix.