[R] Merging levels of matrix dimensions
Anders Nielsen
anielsen at math.ku.dk
Tue Nov 28 12:46:21 CET 2000
Hey
A first try might be something like:
cfsum<-function(X, cf)
{
ret<-matrix(NA, ncol=nlevels(cf), nrow=nrow(X))
for(j in 1:nlevels(cf))ret[,j]<-apply(as.matrix(X[,
cf==levels(cf)[j]]),1,sum)
return(ret)
}
A<-matrix(1:25, 5, 5)
col.f<-as.factor(c("A","B","C","C","C"))
cfsum(A, col.f)
After this we can use the same function on the transposed matrix to
add some of the rows.
Anders
On Tue, 28 Nov 2000, BXC (Bendix Carstensen) wrote:
> If I have a matrix I can sum some of the rows by hand:
> > M
> [,1] [,2] [,3]
> [1,] 1 6 11
> [2,] 2 7 12
> [3,] 3 8 13
> [4,] 4 9 14
> [5,] 5 10 15
> > rbind(M[1,],M[2,]+M[3,],M[4,]+M[5,])
> [,1] [,2] [,3]
> [1,] 1 6 11
> [2,] 5 15 25
> [3,] 9 19 29
>
> This is a trivial special case of the following problem that I
> wuold like to have a solution to:
>
> Consider a matix m, and suppose I have factors f.row and f.rcol
> of lengths dim(m), respectively.
> These factors induce a division of m into submatrices.
> How do I get a nlevels(f.row) by nlevels(f.col) matrix where each
> entry is the sum (or any old function) of the elements in
> each submatrix?
>
> Of course there is an array-generalization of this problem as well.
>
> Any help would be appreaciated.
>
> Bendix
>
> ----------------------
> Bendix Carstensen
> Senior Statistician
> Steno Diabetes Centre
> Niels Steensens Vej 2
> DK-2820 Gentofte
> Denmark
> tel: +45 44 43 87 38
> mob: +45 28 25 87 38
> fax: +45 44 43 73 13
> bxc at novo.dk
> www.biostat.ku.dk/~bxc
> ----------------------
>
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
> Send "info", "help", or "[un]subscribe"
> (in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
>
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list