df <- data.frame(a=factor(c(1,1,2,2,3,3) ), b=c(1,1, 10,10, 20,20) )
a b
1 1 1
2 1 1
3 2 10
4 2 10
5 3 20
6 3 20
I want to split the data frame by column a, calculate b/sum(b) in each group, and put the result in column c. With plyr I can do:
fun <- function(x){
x$c=x$b/sum(x$b)
x
}
ddply(df, .(a), fun )
and have
a b c
1 1 1 0.5
2 1 1 0.5
3 2 10 0.5
4 2 10 0.5
5 3 20 0.5
6 3 20 0.5
but how can I do it with dplyr?
df %.% group_by(a) %.% do(fun)
returns a list instead of a data.frame.