The normal.meth matrix may have duplicate rownames. If the rownames are duplicated, take the median and retain only one row each. For all the rows with unique rownames, keep it as-is. The output should not have duplicate rownames.
library(matrixStats)
normal.meth <- sapply(split.default(normal.meth, colnames(normal.meth)), rowMedians)
Input
> dput(normal.meth[1:5,1:5])
structure(c(0.032865303709292, 0.52090224831803, 0.938794144634782,
0.0245464559203754, 0.0219459912613677, 0.0379074157666324, 0.517612501352023,
0.876290186551959, 0.0327330251402918, 0.0128121186436643, 0.0226085394857827,
0.44294311681768, 0.747965490184437, 0.0181395446476151, 0.0125454991770939,
0.0254179654232608, 0.55890575859087, 0.947559241210409, 0.0193177558971086,
0.0105052884119836, 0.0276096307433916, 0.477774759564032, 0.817474068951357,
0.0278807865780101, 0.0138086173417844), dim = c(5L, 5L), dimnames = list(
c("5S_rRNA", "5S_rRNA", "5S_rRNA", "ABC", "DEF"),
c("TCGA.A4.7288.11", "TCGA.BQ.5880.11", "TCGA.BQ.5879.11",
"TCGA.BQ.5883.11", "TCGA.BQ.7055.11")))
Desired output:
> dput(normal.meth[1:5,1:5])
structure(c(0.0328653,
0.0245464559203754, 0.0219459912613677, 0.03790742,
0.0327330251402918, 0.0128121186436643, 0.02260854,
0.0181395446476151, 0.0125454991770939,
0.02541797, 0.0193177558971086,
0.0105052884119836, 0.02760963,
0.0278807865780101, 0.0138086173417844), dim = c(3L, 5L), dimnames = list(
c("5S_rRNA", "ABC", "DEF"),
c("TCGA.A4.7288.11", "TCGA.BQ.5880.11", "TCGA.BQ.5879.11",
"TCGA.BQ.5883.11", "TCGA.BQ.7055.11")))
>Solution :
Update:
Here’s a way which uses *apply() functions:
vapply(X = unique(rownames(normal.meth)), FUN = \(x) apply(normal.meth[rownames(normal.meth) == x ,, drop = FALSE], 2, median), FUN.VALUE = numeric(ncol(normal.meth)))
Original:
Here’s a roundabout way, using tidyverse functions:
library(tidyverse)
normal.meth |>
as.tibble(rownames = "r")|>
summarise(across(everything(), median), .by = r) |>
column_to_rownames("r") |>
as.matrix()
Output:
TCGA.A4.7288.11 TCGA.BQ.5880.11 TCGA.BQ.5879.11 TCGA.BQ.5883.11
5S_rRNA 0.52090225 0.51761250 0.44294312 0.55890576
ABC 0.02454646 0.03273303 0.01813954 0.01931776
DEF 0.02194599 0.01281212 0.01254550 0.01050529
TCGA.BQ.7055.11
5S_rRNA 0.47777476
ABC 0.02788079
DEF 0.01380862