Learn R Programming

cbcTools (version 0.7.1)

cbc_encode: Encode categorical variables in a CBC design

Description

This function converts categorical variables between different coding schemes. Standard coding keeps categorical variables as-is (factor or character). Dummy coding uses a reference category (all zeros) with indicator variables for other levels. Effects coding uses -1 for the reference category to ensure coefficients sum to zero.

Usage

cbc_encode(data, coding = NULL, ref_levels = NULL)

Value

The input object with specified encoding applied

Arguments

data

A cbc_design or cbc_choices object

coding

Character. Type of encoding: "standard", "dummy", or "effects". If NULL and ref_levels is NULL, data is returned unchanged. If NULL and ref_levels is specified, the current encoding is maintained.

ref_levels

Named list specifying reference levels for categorical variables. For example: list(powertrain = "Gasoline", brand = "A"). If NULL (default), uses the first level of each categorical variable as reference.

Examples

Run this code
library(cbcTools)

# Create profiles with categorical variables
profiles <- cbc_profiles(
  price = c(10, 20, 30),
  quality = c("Low", "Medium", "High"),
  brand = c("A", "B")
)

# Create design (defaults to standard coding)
design <- cbc_design(
  profiles = profiles,
  n_alts = 2,
  n_q = 4
)

# Convert to dummy coding
design_dummy <- cbc_encode(design, coding = "dummy")
head(design_dummy)

# Convert to effects coding
design_effects <- cbc_encode(design, coding = "effects")
head(design_effects)

# Convert back to standard
design_standard <- cbc_encode(design_dummy, coding = "standard")
head(design_standard)

# Custom reference levels with dummy coding
design_dummy2 <- cbc_encode(
  design,
  coding = "dummy",
  ref_levels = list(quality = "Medium", brand = "B")
)
head(design_dummy2)

# Update reference levels without changing encoding
design_updated <- cbc_encode(
  design_dummy,
  ref_levels = list(quality = "High")
)
head(design_updated)

Run the code above in your browser using DataLab