Hi, I have a matrix, say m=matrix(c( 983,679,134, 383,416,84, 2892,2625,570 ),nrow=3 ) i can find its row/col sum by rowSums(m) colSums(m) How do I divide each row/column by its rowSum/colSums and still return in the matrix form? (i.e. the new rowSums/colSums =1) Thanks. Casper -- View this message in context: http://r.789695.n4.nabble.com/how-to-divide-each-column-in-a-matrix-by-its-colSums-tp3062739p3062739.html Sent from the R help mailing list archive at Nabble.com.
Jorge Ivan Velez
2010-Nov-28 20:51 UTC
[R] how to divide each column in a matrix by its colSums?
Hi Casper, Try m/colSums(m) m/rowSums(m) HTH, Jorge On Sun, Nov 28, 2010 at 3:46 PM, casperyc <> wrote:> > Hi, > > I have a matrix, say > m=matrix(c( > 983,679,134, > 383,416,84, > 2892,2625,570 > ),nrow=3 > ) > > i can find its row/col sum by > > rowSums(m) > colSums(m) > > How do I divide each row/column by its rowSum/colSums and still return in > the matrix form? > (i.e. the new rowSums/colSums =1) > > Thanks. > > Casper > > -- > View this message in context: > http://r.789695.n4.nabble.com/how-to-divide-each-column-in-a-matrix-by-its-colSums-tp3062739p3062739.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >[[alternative HTML version deleted]]
In that case, there are values >1, which is clearly not what I wanted. Thanks. I think I should use prop.table -- View this message in context: http://r.789695.n4.nabble.com/how-to-divide-each-column-in-a-matrix-by-its-colSums-tp3062739p3062752.html Sent from the R help mailing list archive at Nabble.com.
Spencer Graves
2010-Nov-28 21:44 UTC
[R] how to divide each column in a matrix by its colSums?
prop.table divides every element by the matrix total, not its colSums: > m <- matrix(1:4, 2) > m [,1] [,2] [1,] 1 3 [2,] 2 4 > prop.table(m) [,1] [,2] [1,] 0.1 0.3 [2,] 0.2 0.4 m/rowSums(m) divides every row by its rowSum: > m/rowSums(m) [,1] [,2] [1,] 0.2500000 0.7500000 [2,] 0.3333333 0.6666667 To divide every element by its colSum: > t(t(m)/rowSums(t(m))) [,1] [,2] [1,] 0.3333333 0.4285714 [2,] 0.6666667 0.5714286 Hope this helps. Spencer On 11/28/2010 12:55 PM, casperyc wrote:> In that case, there are values>1, > which is clearly not what I wanted. > > Thanks. > > I think I should use prop.table
Erich Neuwirth
2010-Nov-28 21:51 UTC
[R] how to divide each column in a matrix by its colSums?
sweep(m,1,rowSums(m),"/") sweep(m,2,colSums(m),"/") On 11/28/2010 9:55 PM, casperyc wrote:> > In that case, there are values >1, > which is clearly not what I wanted. > > Thanks. > > I think I should use prop.table > >