Would like to get a hand on dplyr code, but cannot figure this out. Have seen a similar issue described here for many variables (summarizing counts of a factor with dplyr and Putting rowwise counts of value occurences into new variables, how to do that in R with dplyr?), however my task is somewhat smaller.
Given a data frame, how do I count the frequency of a variable and place that in a new variable.
set.seed(9)
df <- data.frame(
group=c(rep(1,5), rep(2,5)),
var1=round(runif(10,1,3),0))
Then we have:
>df
group var1
1 1 1
2 1 1
3 1 1
4 1 1
5 1 2
6 2 1
7 2 2
8 2 2
9 2 2
10 2 3
Would like a third column indicating per-group (group
) how many times var1
occurs, in this example this would be: count=(4,4,4,4,1,1,3,3,3,1).
I tried - without success - things like:
df %>% group_by(group) %>% rowwise() %>% do(count = nrow(.$var1))
Explanations are very appreciated!