Skip to content

Instantly share code, notes, and snippets.

@acoppock
Created October 6, 2020 15:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acoppock/a82a86f016f05df75f7db3c6174e2e8a to your computer and use it in GitHub Desktop.
Save acoppock/a82a86f016f05df75f7db3c6174e2e8a to your computer and use it in GitHub Desktop.
Some code to simulate a conjoint
# Load packages
library(tidyverse)
library(DeclareDesign)
# helper
Y_function <- function(data) {
data %>%
group_by(pair) %>%
mutate(Y = if_else(E == max(E), 1, 0)) %>%
ungroup
}
# design declaration
# You can change the number of subjects, or pairs to be rated
# You can also change how many attributes and what their levels are.
# You can change what your beliefs are about what the effects will be
design <-
declare_population(
subject = add_level(N = 500),
pair = add_level(N = 4),
candidate = add_level(N = 2, U = runif(N))
) +
declare_assignment(assignment_variable = "A1") +
declare_assignment(assignment_variable = "A2",
conditions = c("young", "middle", "old")) +
declare_assignment(assignment_variable = "A3") +
declare_step(
E =
0.05 * A1 +
0.04 * (A2 == "middle") +
0.08 * (A2 == "old") +
0.02 * A3 + U,
handler = fabricate) +
declare_measurement(handler = Y_function) +
declare_estimator(Y ~ A1 + A2 + A3,
model = lm_robust, term = TRUE)
# Simulate the experiment 500 times
simulations <- simulate_design(design)
# Calculate diagnosands -- here i just did the power
simulations %>%
group_by(term) %>%
summarise(power = mean(p.value <= 0.05))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment