library(tidyverse)

set.seed(2105)
#Assign 5000 opinions on the 4 topics
gas <- rbinom(5000,1, .7)
athletes <- rbinom(5000,1, .2)
pollution <- rbinom(5000,1, .4)
racism <- rbinom(5000,1, .3)
dat <- cbind.data.frame(gas, athletes,pollution, racism)

#The true proportion with racist attitudes is:
mean(dat$racism)
#28.5%

#Randomly assign to treatment
dat$treat <- rbinom(5000,1,.5)

#People in control group add up the first three items, 
#people in the treatment group add up all 4 items

dat |> 
  mutate(count = case_when(treat==0 ~ gas+athletes+pollution,
                           treat==1 ~ gas+athletes+ pollution + racism)) |> 
  group_by(treat) |> 
  summarise(mean(count))

1.63-1.29

set.seed(2102)
true.attitude <- rep(0,1000)
mean(true.attitude)
dat <- as.data.frame(true.attitude)

#Respondents privately flip a coin
dat |> 
  mutate(treatment = sample(c(0,1), 1000, replace=T)) -> dat

#If heads they tell they answer (1), if tails they answer the truth
dat |> 
  mutate(response = case_when(treatment==1 ~ 1, 
                              treatment==0 ~ true.attitude)) -> dat

mean(dat$response)

set.seed(2102)
true.attitude <- rbinom(1000, 1, .4)
mean(true.attitude)
dat <- as.data.frame(true.attitude)

#Respondents privately flip a coin
dat |> 
  mutate(treatment = sample(c(0,1), 1000, replace=T)) -> dat

#If heads they tell they answer (1), if tails they answer the truth
dat |> 
  mutate(response = case_when(treatment==1 ~ 1, 
                              treatment==0 ~ true.attitude)) -> dat

mean(dat$response)
