Skip to content

Instantly share code, notes, and snippets.

@bgall
Last active December 1, 2019 21:23
Show Gist options
  • Save bgall/e90a25b73b80079fd7007fce615f8e5a to your computer and use it in GitHub Desktop.
Save bgall/e90a25b73b80079fd7007fce615f8e5a to your computer and use it in GitHub Desktop.
Wrapped for create_attributes, create_design_df, and create_value_dummies
################################################
# Define function: create_predictors
# Creates randomly generated data sets containing
# all design variables, attributes, and dummy
# variables for the right-hand side of the conjoint
# analysis (excludes the outcome variable),
# based on specified data parameter values.
# Data are "long," sucht hat each row of the data
# is a conjoint profile.
#
# Arguments:
# N: number of participants
# K: number of choices completed
# W: number of profiles per screen
# attr_n: number of attributes overall
# attr_levels: list (or vector)
# of possible levels for each attribute.
# attr_names: names of attributes. defaults a generic
# nmae followed by the index of the attribute
# in attr_levels.
# probs: list (or vector) of probabilities used to randomly
# draw values from the attribute levels vectors and assign
# them to profiles.
################################################
create_predictors <- function(N,
K,
W = 2,
attr_n,
attr_levels,
attr_names = NULL,
probs = NULL) {
# Number of unique profiles (rows in final data frame)
n_profiles <- N * K * W
# Generate design dataframe
temp <- create_design_df(N = N, K = K, W = W)
# Generate specified number of attributes with specified
# properties.
attr_df <- create_attributes(
attr_levels = attr_levels,
n_profiles = n_profiles,
attr_names = attr_names,
probs = probs
)
# If attribute names not provided in function, create vector
# of function-generated attribute namesthe names
if (is.null(attr_names)) {
attr_names <- colnames(attr_df)
}
# Generate dummy variables for each attribute value
temp_attribs <- create_value_dummies(attr_df = attr_df,
attr_levels = attr_levels)
# Combine all attributes, dummies, and design variables into
# a single data frame
df <- dplyr::bind_cols(temp, temp_attribs)
# Return all data created (excludes outcomes)
df
}
#############################################################
# Example
##############################################################
# Specify example parameters for the data
#N <- 50
#K <- 3
#W <- 2
#attr_n <- 3
#attr_levels <- list(c(1, 2, 3), c("a", "b", "c", "d", "e"), c(5))
#attr_names = NULL
#probs = NULL
#
#
# create_predictors(
# N = N,
# K = K,
# W = W,
# attr_n = attr_n,
# attr_levels = attr_levels,
# attr_names = attr_names,
# probs = probs
# )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment