Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate percentages / proportions of values by group using data.table

Tags:

r

data.table

I have a data.table that looks like the following:

x, y, sum(count)
1, 1, 3
1, 2, 7
1, 3, 8
2, 1, 4
2, 2, 3
2, 3, 10

And so on. It's keyed by x and y and I did a sum on a count column. I would like to break it down into percentages by the values of x so that it becomes:

x, y, percentage(counts)
1, 1, 16.7
1, 2, 38.9
1, 3, 44.4
2, 1, 23.5
2, 2, 17.6
2, 3, 58.8

So that the total percentage per x value totals 100%. I am doing this using the data.table package. Thank you in advance for your help.

like image 879
kay Avatar asked Jan 03 '14 18:01

kay


2 Answers

I don't quite understand the data.table solution already posted, so I would do it like this (and I would change the name of the columns to not have parentheses to avoid lots of backtick quoting(!) of column names):

dt[ , `percentage(counts)` := `sum(count)` / sum( `sum(count)` ) * 100 , by = "x" ]
#   x y sum(count) percentage(counts)
#1: 1 1          3           16.66667
#2: 1 2          7           38.88889
#3: 1 3          8           44.44444
#4: 2 1          4           23.52941
#5: 2 2          3           17.64706
#6: 2 3         10           58.82353
like image 113
Simon O'Hanlon Avatar answered Sep 20 '22 20:09

Simon O'Hanlon


On your original (not summed) data, you could do:

allsums <- sum(data[, counts])
data[, percentage = 100*sum(counts)/allsums, by="x,y"]

Or on your summed data:

allsums <- sum(data[, sums])
data[, percentage = 100*sums/allsums, by="x,y"]
like image 22
Noam Ross Avatar answered Sep 19 '22 20:09

Noam Ross