Takes a two-dimensional matrix and collapses row or columns according to a specified function.
collapse_matrix(x, groups, dim = 1, FUN = sum)
x | A |
---|---|
groups | A vector or factor of the same length as the rows or columns of x, which indicates which elements to collapse. |
dim | Which dimension to collapse. 1 for rows and 2 for columns |
FUN | Function (or function name) to apply to elements per groups |
Returns a matrix
object.
This function uses plyr functions to aggregate columnwise or rowwise according to a grouping factor.
x <- cbind(rbind(matrix(0,2,2),matrix(1,2,2)), rbind(matrix(1,2,2),matrix(0,2,2))) colnames(x) <- c("C1","C2","C3","C4") row.names(x) <- c("R1","R2","R3","R4") x#> C1 C2 C3 C4 #> R1 0 0 1 1 #> R2 0 0 1 1 #> R3 1 1 0 0 #> R4 1 1 0 0collapse_matrix(x=x,groups = rep(c(1,2),each=2),dim=1,FUN=sum)#> X1 #> C1 C2 C3 C4 #> 1 0 0 2 2 #> 2 2 2 0 0collapse_matrix(x=x,groups = rep(c(1,2),each=2),dim=2,FUN=mean)#> #> X1 1 2 #> R1 0 1 #> R2 0 1 #> R3 1 0 #> R4 1 0