Spaces:
Sleeping
Sleeping
rodrigoheldt
Add Insights tab: Gamma heatmap, SoP by segment, slopegraph, beta distributions, strategic quadrant
6a30d28 Download _Main_Generalized.R from rodrigoheldt/bws_case1_app: direct link, hf CLI and curl.
- Browser
- Download file 12.8 kB
-
https://huggingface.co/spaces/rodrigoheldt/bws_case1_app/resolve/main/_Main_Generalized.R
- Command line
-
hf download hf://spaces/rodrigoheldt/bws_case1_app/_Main_Generalized.R
-
curl -L -o _Main_Generalized.R https://huggingface.co/spaces/rodrigoheldt/bws_case1_app/resolve/main/_Main_Generalized.R
12.8 kB
| # ============================================================================== | |
| # _Main_Generalized.R – Versão generalizada de _Main.R | |
| # | |
| # Ponto de entrada: seção 1.3 — o usuário fornece diretamente o arquivo | |
| # dataMlogit.csv, eliminando a dependência do pipeline Qualtrics. | |
| # | |
| # Estrutura idêntica ao _Main.R original a partir da seção 2. | |
| # Modelos: MNL · MXL · MXL-Hier (todos via pacote gmnl) | |
| # ============================================================================== | |
| # ============================================================================== | |
| # PARÂMETROS DO USUÁRIO <<< EDITE APENAS ESTA SEÇÃO >>> | |
| # ============================================================================== | |
| # 1. Caminho para o arquivo dataMlogit no formato padronizado | |
| dataMlogitFile <- "Data/dataMlogit.csv" | |
| # 2. Variáveis de segmentação ORIGINAIS presentes em dataMlogit | |
| # (colunas categóricas, ex: "Usage" — não as dummies "Usage_Medium") | |
| segmentationVars <- c("NCards", "Usage", "Age", "Education") | |
| # 3. Radical da variável de segmentação a usar no MXL-Hier (heterog. observada) | |
| # O código detecta automaticamente as dummies correspondentes. | |
| # Exemplo: "Usage_" → detecta Usage_Medium, Usage_High, etc. | |
| segmentationVarsRadical <- "Usage_" | |
| # 4. Número de draws para os modelos Mixed Logit (MXL e MXL-Hier) | |
| nDraws <- 200 # Halton sequences converge com menos draws que Monte Carlo (haltons=NA) | |
| # 5. Rótulo do segmento de REFERÊNCIA do MXL-Hier (categoria omitida nas dummies) | |
| # Exemplo: segmentationVarsRadical = "Usage_" → referência = "Usage_Low" | |
| referenceSegmentLabel <- "Usage_Low" | |
| # 6. Segmentos a comparar no slopegraph (seção 7.3) | |
| slopegraphFrom <- "Usage_Low" | |
| slopegraphTo <- "Usage_High" | |
| # 7. Variável categórica original usada no MXL-Hier (para distribuição de beta_i) | |
| # = nome da coluna categórica em dataMlogit (sem o sufixo "_") | |
| hierSegmentVarCategorical <- "Usage" | |
| # 8. Número de atributos top para a distribuição de beta_i (seção 7.4) | |
| nTopAttributes <- 6 | |
| # 5. (Opcional) Arquivo CSV com mapeamento labelId → rótulo legível | |
| # Colunas: labelId (ex: "T1"), label (ex: "Cashback nas compras") | |
| # Deixe NULL para usar os próprios labelIds como rótulos | |
| attributeLabelFile <- "Data/attributeLabel.csv" | |
| # ============================================================================== | |
| # FIM DOS PARÂMETROS DO USUÁRIO | |
| # ============================================================================== | |
| #### 1. Carregamento de pacotes e funções ###################################### | |
| library(gmnl) | |
| library(mlogit) | |
| library(tidyverse) | |
| library(stringr) | |
| library(fastDummies) | |
| library(lmtest) | |
| library(ggrepel) | |
| source("Functions/CreateResultCount.R") | |
| source("Functions/ShareOfPreferencesMnlMixl.R") | |
| source("Functions/ShareOfPreferencesMixlHier.R") | |
| source("Functions/MakeFormulaMixlHier.R") | |
| source("Functions/SegmentationAnalysis.R") | |
| source("Functions/files2/ShareOfPreferencesBySegment.R") | |
| source("Functions/files2/PlotGammaHeatmap.R") | |
| source("Functions/files2/PlotShareOfPreferencesBySegment.R") | |
| source("Functions/files2/PlotAttributeRankingSlopegraph.R") | |
| source("Functions/files2/PlotBetaDistributionsBySegment.R") | |
| source("Functions/files2/PlotStrategicQuadrant.R") | |
| # 1.3. Carregar dataMlogit (ponto de entrada generalizado) --------------------- | |
| dataMlogit <- read.csv( | |
| file = dataMlogitFile, | |
| header = TRUE, | |
| sep = "," | |
| ) %>% | |
| mutate( | |
| Response = as.logical(Response), | |
| Str = as.character(Str), | |
| Id = as.integer(Id), | |
| Q = as.integer(Q), | |
| Pair = as.integer(Pair) | |
| ) | |
| # 1.4. Detectar colunas de atributos e rótulos --------------------------------- | |
| attributeCols <- sort(names(dataMlogit)[grepl("^T[0-9]+$", names(dataMlogit))]) | |
| message("Atributos detectados (", length(attributeCols), "): ", | |
| paste(attributeCols, collapse = ", ")) | |
| if (!is.null(attributeLabelFile) && file.exists(attributeLabelFile)) { | |
| attributeLabel <- read.csv(attributeLabelFile, stringsAsFactors = FALSE) | |
| } else { | |
| attributeLabel <- data.frame(labelId = attributeCols, label = attributeCols, | |
| stringsAsFactors = FALSE) | |
| } | |
| # 1.5. Extrair características individuais direto do dataMlogit --------------- | |
| segVarsPresent <- segmentationVars[segmentationVars %in% names(dataMlogit)] | |
| indCharacteristics <- dataMlogit %>% | |
| distinct(Id, .keep_all = TRUE) %>% | |
| select(Id, all_of(segVarsPresent)) | |
| # 1.6. Preparar dados no formato mlogit.data (necessário para gmnl) ----------- | |
| dataMlogitGmnl <- mlogit.data( | |
| data = dataMlogit, | |
| choice = "Response", | |
| shape = "long", | |
| chid.var = c("Str", "Id"), | |
| alt.var = "Pair" | |
| ) | |
| # ============================================================================== | |
| # 2. Análise de contagem | |
| # ============================================================================== | |
| resultCount <- CreateResultCount( | |
| dataMlogit = dataMlogit | |
| ) | |
| print(resultCount) | |
| # ============================================================================== | |
| # 3. Multinomial Logit (MNL) | |
| # ============================================================================== | |
| resultMnl <- gmnl( | |
| formula = as.formula( | |
| paste0( | |
| "Response ~ ", | |
| str_c(resultCount %>% filter(Rank != max(Rank)) %>% pull(labelId), | |
| collapse = " + "), | |
| " - 1 | 0" | |
| ) | |
| ), | |
| data = dataMlogitGmnl, | |
| model = "mnl" | |
| ) | |
| summary(resultMnl) | |
| # 3.1. AIC e Log-Likelihood | |
| AIC(resultMnl) | |
| logLik(resultMnl) | |
| # 3.2. Share of Preferences | |
| shareOfPreferencesMnl <- ShareOfPreferencesMnlMixl( | |
| resultModelOutput = resultMnl, | |
| resultCount = resultCount | |
| ) | |
| print(shareOfPreferencesMnl) | |
| # ============================================================================== | |
| # 4. Mixed Logit – heterogeneidade NÃO observada (MXL) | |
| # ============================================================================== | |
| # 4.1. Vetor de parâmetros aleatórios (distribuição normal para todos) | |
| random_params <- setNames( | |
| rep("n", nrow(resultCount) - 1), | |
| resultCount %>% filter(Rank != max(Rank)) %>% pull(labelId) | |
| ) | |
| # 4.2. Estimação | |
| resultMxl <- gmnl( | |
| formula = as.formula( | |
| paste0( | |
| "Response ~ ", | |
| str_c(resultCount %>% filter(Rank != max(Rank)) %>% pull(labelId), | |
| collapse = " + "), | |
| " - 1 | 0" | |
| ) | |
| ), | |
| data = dataMlogitGmnl, | |
| model = "mixl", | |
| ranp = random_params, | |
| panel = TRUE, | |
| id.var = "Id", | |
| R = nDraws, | |
| haltons = NULL, # Halton sequences: convergência ~3-5x mais rápida | |
| cores = parallel::detectCores() - 1 # Usar todos os núcleos menos 1 | |
| ) | |
| summary(resultMxl) | |
| # 4.3. AIC e Log-Likelihood | |
| AIC(resultMxl) | |
| logLik(resultMxl) | |
| # 4.4. Share of Preferences | |
| shareOfPreferencesMxl <- ShareOfPreferencesMnlMixl( | |
| resultModelOutput = resultMxl, | |
| resultCount = resultCount | |
| ) | |
| print(shareOfPreferencesMxl) | |
| # ============================================================================== | |
| # 5. Mixed Logit Hierárquico – heterogeneidade OBSERVADA (MXL-Hier) | |
| # ============================================================================== | |
| # 5.1. Detectar automaticamente as colunas dummy do radical informado | |
| # Ex: segmentationVarsRadical = "Usage_" → c("Usage_Medium","Usage_High") | |
| hierDummyCols <- dataMlogit %>% | |
| select(starts_with(segmentationVarsRadical)) %>% | |
| colnames() | |
| message("Variáveis de heterogeneidade observada (", length(hierDummyCols), "): ", | |
| paste(hierDummyCols, collapse = ", ")) | |
| # 5.2. Construir fórmula e parâmetros via MakeFormulaMixlHier | |
| formulaMixlHier <- MakeFormulaMixlHier( | |
| segmentationVars = hierDummyCols, | |
| resultCount = resultCount | |
| ) | |
| # 5.3. Estimação | |
| resultMxlHier <- gmnl( | |
| formula = formulaMixlHier$formulaMixlHier, | |
| data = dataMlogitGmnl, | |
| model = "mixl", | |
| ranp = formulaMixlHier$randomParams, | |
| mvar = formulaMixlHier$mVar, | |
| panel = TRUE, | |
| id.var = "Id", | |
| R = nDraws, | |
| haltons = NULL, # Halton sequences: convergência ~3-5x mais rápida | |
| cores = parallel::detectCores() - 1 # Usar todos os núcleos menos 1 | |
| ) | |
| summary(resultMxlHier) | |
| # 5.4. AIC e Log-Likelihood | |
| AIC(resultMxlHier) | |
| logLik(resultMxlHier) | |
| # 5.5. Share of Preferences | |
| shareOfPreferencesMxlHier <- ShareOfPreferencesMixlHier( | |
| resultModelOutput = resultMxlHier, | |
| resultCount = resultCount, | |
| dataMlogit = dataMlogit, | |
| mVarList = formulaMixlHier$mVar | |
| ) | |
| print(shareOfPreferencesMxlHier) | |
| # ============================================================================== | |
| # 6. Likelihood Ratio Tests (LRT) | |
| # ============================================================================== | |
| # 6.1. MNL vs MXL (testa se heterogeneidade não observada é relevante) | |
| lrtest(resultMnl, resultMxl) | |
| # 6.2. MXL vs MXL-Hier (testa se heterogeneidade observada acrescenta) | |
| lrtest(resultMxl, resultMxlHier) | |
| # ============================================================================== | |
| # 7. Segmentação por variáveis demográficas/comportamentais (via MXL indpar) | |
| # ============================================================================== | |
| # Extrair parâmetros individuais do gmnl ($bi = array [Id, R, beta]) | |
| indpar_matrix <- apply(resultMxl$bi, c(1, 3), mean) | |
| indpar_df <- as.data.frame(indpar_matrix) %>% | |
| mutate(id = sort(unique(dataMlogit$Id))) %>% | |
| select(id, everything()) | |
| if (!dir.exists("Results")) dir.create("Results") | |
| for (segVar in segVarsPresent) { | |
| message("Segmentação por: ", segVar) | |
| assign( | |
| paste0("segmentation", segVar), | |
| SegmentationAnalysis( | |
| indpar = indpar_df, | |
| indCharacteristics = indCharacteristics, | |
| segmentationVar = segVar | |
| ) | |
| ) | |
| } | |
| # ============================================================================== | |
| # FORMATO ESPERADO DE dataMlogit (referência rápida) | |
| # ============================================================================== | |
| # Id, Q, Str, Best, Worst, Pair, ResponseBest, ResponseWorst, Response, | |
| # T1..Tn (dummies +1/-1/0 por atributo), | |
| # [segVars originais], [dummies de segVars] | |
| # Ver Data/README.txt para descrição completa. | |
| # ============================================================================== | |
| # ============================================================================== | |
| # 7. Post-hoc insights do MXL-Hier (heterogeneidade observada) | |
| # Equivalente ao _MainHeterogeneityInsights.R original. | |
| # ============================================================================== | |
| # 7.1. Heatmap dos coeficientes Gamma | |
| # Visualiza o quanto cada segmento desloca a preferência média de cada atributo | |
| # em relação ao grupo de referência. | |
| heatmapGamma <- PlotGammaHeatmap( | |
| resultModelOutput = resultMxlHier, | |
| resultCount = resultCount, | |
| segmentationVars = hierDummyCols, | |
| attributeLabel = attributeLabel | |
| ) | |
| print(heatmapGamma$plot) | |
| # 7.2. Share of Preferences por segmento | |
| # Calcula o SoP para perfis sintéticos de cada segmento usando os Gamma estimados. | |
| sopBySegment <- PlotShareOfPreferencesBySegment( | |
| resultModelOutput = resultMxlHier, | |
| resultCount = resultCount, | |
| mVarList = formulaMixlHier$mVar, | |
| segmentationVars = hierDummyCols, | |
| referenceSegmentLabel = referenceSegmentLabel, | |
| attributeLabel = attributeLabel | |
| ) | |
| print(sopBySegment$plot) | |
| # 7.3. Slopegraph de mudança de ranking entre segmentos | |
| # Atributos que sobem indicam oportunidade de diferenciação no segmento de destino. | |
| slopegraph <- PlotAttributeRankingSlopegraph( | |
| sopBySegmentData = sopBySegment$data, | |
| fromSegment = slopegraphFrom, | |
| toSegment = slopegraphTo | |
| ) | |
| print(slopegraph$plot) | |
| # 7.4. Distribuição de beta_i por segmento (via effect.gmnl) | |
| # Extrai estimativas individuais condicionais e as distribui por segmento. | |
| betaDist <- PlotBetaDistributionsBySegment( | |
| resultModelOutput = resultMxlHier, | |
| resultCount = resultCount, | |
| dataMlogit = dataMlogit, | |
| attributeLabel = attributeLabel, | |
| segmentVar = hierSegmentVarCategorical, | |
| nTopAttributes = nTopAttributes | |
| ) | |
| print(betaDist$plot) | |
| # 7.5. Quadrante estratégico 2×2 | |
| # Mapeia cada atributo em (importância média) × (variabilidade entre segmentos). | |
| # Quadrantes sugerem ações estratégicas distintas por atributo. | |
| quadrant <- PlotStrategicQuadrant( | |
| sopBySegmentData = sopBySegment$data, | |
| referenceSegment = referenceSegmentLabel | |
| ) | |
| print(quadrant$plot) | |
| # 7.6. Tabela consolidada de insights estratégicos | |
| insightsTable <- quadrant$data %>% | |
| arrange(desc(meanShare)) %>% | |
| mutate( | |
| meanShare = scales::percent(meanShare, accuracy = 0.1), | |
| shareRange = scales::percent(shareRange, accuracy = 0.1) | |
| ) | |
| print(insightsTable) | |
| # write.csv(insightsTable, "Results/strategic_insights.csv", row.names = FALSE) | |