# Perform quantile normalization on a numeric matrix 'data_matrix'
quantile_normalize <- function(data_matrix) {
# Step 1: Sort each column
sorted_data <- apply(data_matrix, 2, sort)
# Step 2: Calculate the mean of each row across sorted columns
row_means <- rowMeans(sorted_data)
# Step 3: Replace each column's sorted values with the row means
sorted_data <- matrix(row_means, nrow = nrow(sorted_data), ncol = ncol(sorted_data), byrow = TRUE)
# Step 4: Unsort the columns to their original order
rank_indices <- apply(data_matrix, 2, order)
normalized_data <- matrix(nrow = nrow(data_matrix), ncol = ncol(data_matrix))
for (i in 1:ncol(data_matrix)) {
normalized_data[, i] <- sorted_data[rank_indices[, i], i]
}
return(normalized_data)
}
Make a quantile_normalization function
Example here: https://www.spsanderson.com/steveondata/posts/2024-03-28/