Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr: calculate group weights

Tags:

r

dplyr

Quick question, how to calculate group weights using dplyr?

For example, given data:

D = data.frame(cat=rep(LETTERS[1:2], each=2), val=1:4)

#   cat val
# 1   A   1
# 2   A   2
# 3   B   3
# 4   B   4

The desired result should be:

#   cat weight
# 1   A    0.3     # (1+2)/10
# 2   B    0.7     # (3+4)/10

Anything more succinct than the following?

D %>% 
  mutate(total=sum(val)) %>% 
  group_by(cat) %>% 
  summarise(weight=sum(val/total))
like image 213
Daniel Krizian Avatar asked Dec 19 '22 10:12

Daniel Krizian


1 Answers

I'd write it as

D <- data.frame(
  cat = rep(LETTERS[1:2], each = 2), 
  val = 1:4
)

D %>% 
  group_by(cat) %>%
  summarise(val = sum(val)) %>%
  mutate(weight =  val / sum(val))

Which you can simplify a little using count() (only in dplyr >= 0.3) and prop.table():

D %>% 
  count(cat, wt = val) %>%
  mutate(weight = prop.table(n))
like image 78
hadley Avatar answered Jan 09 '23 11:01

hadley