Skip to content

Instantly share code, notes, and snippets.

@wulingyun
Created June 19, 2016 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wulingyun/9f982f940b7275e16d6e7f5034a31132 to your computer and use it in GitHub Desktop.
Save wulingyun/9f982f940b7275e16d6e7f5034a31132 to your computer and use it in GitHub Desktop.
Merge matrix rows with same name
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