Question

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.

Was it helpful?

Solution

df %>%
  group_by(a) %>%
  mutate(c=b/sum(b))

  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

OTHER TIPS

Just to mention an R base solution, you can use transform (R base equivalent to mutate) and ave function to split vectors and apply functions.

> transform(df, c=ave(b,a, FUN= function(b) b/sum(b)))
  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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top