0

I have a table and I would like to calculate the percentage of each value on the sum of each column. I mean I would like to have these data:

(30/35)x100, (0/35)x100, (5/35)x100 for the first column, (3/29)x100, (24/29)x100, (2/29)x100 and (5/19)x100, (7/19)x100, (7/19)x100 for the third column.

df
       Donkey Horse Hybrid
  Donkey     30     3      5
  Horse       0    24      7
  Hybrid      5     2      7

I used this function but the calculation is not correct.

apply(df, 2,function(x,y) (x/y)*100,  colSums(df))

Could anyone help please? Many thanks in advance

Azy
  • 65
  • 8
  • See also [Calculate row-wise proportions](https://stackoverflow.com/questions/16032826/calculate-row-wise-proportions), but change margins to columns as necessary – Henrik Jul 13 '21 at 20:17

3 Answers3

3

You can try propotions like below

> proportions(as.matrix(df), 2) * 100
         Donkey     Horse   Hybrid
Donkey 85.71429 10.344828 26.31579
Horse   0.00000 82.758621 36.84211
Hybrid 14.28571  6.896552 36.84211

or with colSums + col like below

> df / colSums(df)[col(df)] * 100
         Donkey     Horse   Hybrid
Donkey 85.71429 10.344828 26.31579
Horse   0.00000 82.758621 36.84211
Hybrid 14.28571  6.896552 36.84211
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
3

In the OP's code, the syntax should be

apply(df, 2, function(x) x/sum(x) * 100)
        Donkey     Horse   Hybrid
Donkey 85.71429 10.344828 26.31579
Horse   0.00000 82.758621 36.84211
Hybrid 14.28571  6.896552 36.84211

data

df <- structure(list(Donkey = c(30L, 0L, 5L), Horse = c(3L, 24L, 2L
), Hybrid = c(5L, 7L, 7L)), class = "data.frame", row.names = c("Donkey", 
"Horse", "Hybrid"))
akrun
  • 874,273
  • 37
  • 540
  • 662
3

Any of the following can also work:

prop.table(as.matrix(df), 2)*100
         Donkey     Horse   Hybrid
Donkey 85.71429 10.344828 26.31579
Horse   0.00000 82.758621 36.84211
Hybrid 14.28571  6.896552 36.84211


sweep(df, 2, colSums(df), '/')*100
         Donkey     Horse   Hybrid
Donkey 85.71429 10.344828 26.31579
Horse   0.00000 82.758621 36.84211
Hybrid 14.28571  6.896552 36.84211

t(t(df)/ colSums(df))*100
         Donkey     Horse   Hybrid
Donkey 85.71429 10.344828 26.31579
Horse   0.00000 82.758621 36.84211
Hybrid 14.28571  6.896552 36.84211
Onyambu
  • 67,392
  • 3
  • 24
  • 53