[R] Calculating column percentages of a table

Chuck Cleland ccleland at optonline.net
Sat Jun 2 23:07:59 CEST 2007


Rehceb Rotkiv wrote:
> Hello,
> 
> I know, this is a real newbie question, but I can't find anything on this in
> the manuals! I know that I get calculate the column totals of a table with
> `apply(mytable, 2, sum)'. Now I want each column total to be 100% and
> calculate the percentage of each field of the column. How would I do that?
> Rcommander, the ultimate newb-tool, has a function `colPercents' which is
> exactly what I need, but I do not want to load the whole thing into memory
> just for this function. Is there a way to load just this single function
> from the Rcmdr package?

  Does this help?

> mymat <- matrix(sample(1:10, 40, replace=TRUE), ncol=4)

> mymat
      [,1] [,2] [,3] [,4]
 [1,]    9    2    5    8
 [2,]    8    5    2    3
 [3,]    4    1    5    8
 [4,]    9    8    6    7
 [5,]    7   10    7   10
 [6,]    1    9    5    4
 [7,]   10   10    1    3
 [8,]    5    3    5    7
 [9,]    6    1    8    6
[10,]    1    6   10    9

> prop.table(mymat, margin=2)*100
           [,1]      [,2]      [,3]      [,4]
 [1,] 15.000000  3.636364  9.259259 12.307692
 [2,] 13.333333  9.090909  3.703704  4.615385
 [3,]  6.666667  1.818182  9.259259 12.307692
 [4,] 15.000000 14.545455 11.111111 10.769231
 [5,] 11.666667 18.181818 12.962963 15.384615
 [6,]  1.666667 16.363636  9.259259  6.153846
 [7,] 16.666667 18.181818  1.851852  4.615385
 [8,]  8.333333  5.454545  9.259259 10.769231
 [9,] 10.000000  1.818182 14.814815  9.230769
[10,]  1.666667 10.909091 18.518519 13.846154

> colSums(prop.table(mymat, margin=2)*100)
[1] 100 100 100 100

> Many thanks,
> Rehceb Rotkiv

-- 
Chuck Cleland, Ph.D.
NDRI, Inc.
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894



More information about the R-help mailing list