Q:

dplyr: save count as a new variable

I used the following to create a dataframe.
set.seed(9)
df <- data.frame(
    group=c(rep(1,5), rep(2,5)),
    var1=round(runif(10,1,3),0))

Then, I use the following to count number of rows per group:
df %>% add_count(group, name="GSIZE")

Then, I try to calculate a new variable:
df$var2<-df$var1+df$GSIZE

That's when I get the error message below:

Error in $<-.data.frame(*tmp*, var2, value = numeric(0)) : 
    replacement has 0 rows, data has 10

Any ideas on how to fix this? It seems like GSIZE was not treated as a variable saved in the data frame df.

A:

You have to be explicit about an assignment in R. But, for the problem at hand, this suffices. 
    set.seed(9)
    df <- data.frame(
    group=c(rep(1,5), rep(2,5)),
    var1=round(runif(10,1,3),0)) %>% 
    add_count(group, name="GSIZE") %>% 
    mutate(var2 = var1+GSIZE)

