Similar to dplyr: put count occurrences into new variable, Putting rowwise counts of value occurences into new variables, how to do that in R with dplyr?, Count observations of distinct values per group and add a new column of counts for each value or Create columns from factors and count
I am looking for a way to summarize observations under a certain grouping variable and attach the result to my dataframe (preferably with dplyr, but any solution is appreciated).
Here is the structure of my data:
id team teamsize apr16 may16
123 A 13 0 1
124 B 8 1 1
125 A 13 1 0
126 A 13 0 1
I would like R to group my data according to the teams, count the number of 1 for apr16 (so just add up the 1 for each team) and attach a new variable to my dataframe with the result. In a next step, I would like to use this result (it represents numbers of users of a certain policy) in order to calculate the share of users for each Team (that's what I need teamsize for) - but I haven gotten there yet.
I have tried several ways to just calculate the number of users, but it did not work out.
DF <- DF%>%
group_by(team, apr16) %>%
mutate(users_0416 = n()) %>%
ungroup
DF <- DF%>%
group_by(team, apr16) %>%
mutate(users_0416 = sum()) %>%
ungroup
I feel like this is a really easy thing to do but I am just not moving on and really looking forward to any help.