Calculate average by group

See the FAQ: How to do a minimal reproducible example reprex for beginners. Most of the pieces are here, but some glitches exist, such as

that requires reverse engineering to address the problems in the terms posed. A reprex has the advantage of running "as-is" on another's RStudio session.

Couple of pointers before getting to an example using simpler data

  1. Use snake_case rather than dotted.separators as a matter of good style
  2. don't name objects df, data, date or other words that are built-in functions or functions loaded by libraries; some operations give precedence to the function name
  3. Anything in a Stats 101 textbook has a function already written. Instead of


subscribe <- rbinom(n=n_pop, size=1, prob=0.5)
  1. Construct data frames directly
DF <- data.frame(subscribe = subscribe, see_ad = see_ad, buy = buy)

Here is fake data composed of binary outcomes illustrating contingency tables with count and with proportion results.

N <- 100
exposed <- rbinom(n=N, size=1, prob=0.25)
purchased <- rbinom(n=N, size=1, prob=0.05)
DF <- data.frame(exposed = as.factor(exposed),purchased = as.factor(purchased))
#>        purchased
#> exposed  0  1
#>       0 72  2
#>       1 25  1
#>        purchased
#> exposed    0    1
#>       0 0.72 0.02
#>       1 0.25 0.01
1 Like