Created
June 19, 2016 10:38
-
-
Save wulingyun/9f982f940b7275e16d6e7f5034a31132 to your computer and use it in GitHub Desktop.
Merge matrix rows with same name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
merge_rows <- function(x, method=mean, na.rm=FALSE) | |
{ | |
x <- as.matrix(x[!is.na(rownames(x)), ]) | |
r <- unique(rownames(x)) | |
m <- length(r) | |
if (dim(x)[1] != m) { | |
y <- matrix(nrow=m, ncol=dim(x)[2]) | |
rownames(y) <- r | |
colnames(y) <- colnames(x) | |
for (i in 1:m) { | |
n <- sum(rownames(x) == r[i]) | |
if (n > 1) { | |
s <- as.matrix(x[rownames(x) == r[i], ]) | |
y[i, ] <- apply(s, 2, method, na.rm) | |
} | |
else { | |
y[i, ] <- x[r[i], ] | |
} | |
} | |
} | |
else { | |
y <- x | |
} | |
y | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment