#**************************************************************************
# Conjoint analysis: a case study on the quality of banana
# Le, Le & Nguyen - SPISE2014
# verR.3.1.2 - Update: 05.12.2014
#**************************************************************************

# install.packages("conjoint")       # Traditional conjoint analysis
                                     #     with multiple linear reg.
# install.packages("AlgDesign")      # Fractional factorial design
# install.packages("clusterSim")     # segmentation 
# install.packages("agricolae")      # design Graeco design

# Load packages -----------------------------------------------------------

library(FactoMineR)
library(SensoMineR)
library(ggplot2)
library(scales)
library(reshape2)
library(holos)
library(knitr)
library(conjoint)
library(AlgDesign)
library(clusterSim)
## Loading required package: cluster
## Loading required package: MASS
rm(list=ls())
options(max.print=5.5E5)           # Max print

# wd <- "C:/Users/Tam Minh Le/Dropbox/10. Project/26. Banana/02. Data"
wd <- "C:/Users/LE Minh-Tam/Dropbox/10. Project/26. Banana/02. Data"

# Create data frame: Experimental design ----------------------------------
exp.design <- matrix(c(1, 1, 1, 1, 
                       1, 2, 3, 2, 
                       1, 3, 2, 3, 
                       2, 1, 3, 3,
                       2, 2, 2, 1,
                       2, 3, 1, 2, 
                       3, 1, 2, 2,
                       3, 2, 1, 3,
                       3, 3, 3, 1), ncol=4, nrow=9, byrow=TRUE) 
rownames(exp.design) <- paste("prof.", 1:9, sep="")
colnames(exp.design) <- c("color", "shape", "bruise", "cigar")
exp.design <- as.data.frame(exp.design)


# Create data frame: levels -----------------------------------------------
color <- c("green", "green-yellow", "yellow")
shape <- c("high.heterogeneity", "heterogeneity", "homogeneity")
bruise <- c("high.bruise", "bruise", "non.bruise")
cigar.end.rot <- c("high.cigar", "med.cigar", "non.cigar")
lev.names <- data.frame(c(color, shape, bruise, cigar.end.rot)) 
colnames(lev.names) <- "levels"
lev.names
##                levels
## 1               green
## 2        green-yellow
## 3              yellow
## 4  high.heterogeneity
## 5       heterogeneity
## 6         homogeneity
## 7         high.bruise
## 8              bruise
## 9          non.bruise
## 10         high.cigar
## 11          med.cigar
## 12          non.cigar
# Create data frame: quality score ----------------------------------------
# nha: 
setwd(wd)
ba.qual <- read.csv("quality.csv", sep=";", dec=".", header=TRUE, row.names=1)
quality <- ba.qual[,seq(1, ncol(ba.qual), by=3)] 

quality$id <- rownames(quality)
qual <- as.data.frame(melt(quality), quote=FALSE) # long.table
## Using id as id variables
qual.score <- qual[,3]

## Classification based on quality score 
res.PCA <- PCA(quality[,1:32], graph=FALSE)
# HCPC(res.PCA$ind$coord, nb.clust=3, consol=TRUE)

# Conjoint analysis -------------------------------------------------------

Conjoint(qual.score, exp.design, lev.names)
## 
## Call:
## lm(formula = frml)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -723,31 -131,70   -2,73  127,70  657,75 
## 
## Coefficients:
##                   Estimate Std. Error t value Pr(>|t|)    
## (Intercept)        451,594     12,267  36,813  < 2e-16 ***
## factor(x$color)1   -43,500     17,349  -2,507   0,0127 *  
## factor(x$color)2    16,688     17,349   0,962   0,3369    
## factor(x$shape)1    -2,656     17,349  -0,153   0,8784    
## factor(x$shape)2  -106,385     17,349  -6,132 2,95e-09 ***
## factor(x$bruise)1 -173,125     17,349  -9,979  < 2e-16 ***
## factor(x$bruise)2  -71,240     17,349  -4,106 5,29e-05 ***
## factor(x$cigar)1   -16,500     17,349  -0,951   0,3424    
## factor(x$cigar)2    28,146     17,349   1,622   0,1059    
## ---
## Signif. codes:  0 '***' 0,001 '**' 0,01 '*' 0,05 '.' 0,1 ' ' 1
## 
## Residual standard error: 208,2 on 279 degrees of freedom
## Multiple R-squared:  0.4922, Adjusted R-squared:  0.4776 
## F-statistic:  33.8 on 8 and 279 DF,  p-value: < 2,2e-16
## [1] "Part worths (utilities) of levels (model parameters for whole sample):"
##                levnms      utls
## 1           intercept  451,5938
## 2               green     -43,5
## 3        green-yellow   16,6875
## 4              yellow   26,8125
## 5  high.heterogeneity   -2,6562
## 6       heterogeneity -106,3854
## 7         homogeneity  109,0417
## 8         high.bruise  -173,125
## 9              bruise  -71,2396
## 10         non.bruise  244,3646
## 11         high.cigar     -16,5
## 12          med.cigar   28,1458
## 13          non.cigar  -11,6458
## [1] "Average importance of factors (attributes):"
## [1] 17,68 23,45 45,62 13,25
## [1] Sum of average importance:  100
## [1] "Chart of average factors importance"
# caSegmentation(qual.score, exp.design, 2)
# ShowAllUtilities(qual.score, exp.design, lev.names) # estimating all models 
# utility <- ShowAllUtilities(qual.score, exp.design, lev.names)


# Conjoint analysis by hand -----------------------------------------------

## A experimental design for 32 subjects
design <- exp.design
design$id <- rownames(design)
df <- design[rep(1:nrow(design),each=32),] 
rownames(df) <- NULL 
# df

## A vector of quality score for 32 subjects
t.hedo <- t(ba.qual[,seq(1, ncol(ba.qual), by=3)])
hedo.anova <- as.matrix(t.hedo)
hedo <- melt(hedo.anova, id=1)
colnames(hedo) = c("subject","product","score")
hedo.plan <- cbind(df, hedo)


## model1: variables are considered as continuous variables
## For understand, dont use
# model1 <- aov(score ~ color + shape + bruise + cigar, data=hedo.plan) 
# summary(model1) # factors: bruise > shape > color

## model2: varibales are considered as dummy variables
model2 <- lm(score ~ factor(color) + factor(shape) + factor(bruise) + factor(cigar), 
             data=hedo.plan)
summary(model2)
## 
## Call:
## lm(formula = score ~ factor(color) + factor(shape) + factor(bruise) + 
##     factor(cigar), data = hedo.plan)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -723.31 -131.70   -2.73  127.70  657.75 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)      451.594     12.267  36.813  < 2e-16 ***
## factor(color)1   -43.500     17.349  -2.507   0.0127 *  
## factor(color)2    16.688     17.349   0.962   0.3369    
## factor(shape)1    -2.656     17.349  -0.153   0.8784    
## factor(shape)2  -106.385     17.349  -6.132 2.95e-09 ***
## factor(bruise)1 -173.125     17.349  -9.979  < 2e-16 ***
## factor(bruise)2  -71.240     17.349  -4.106 5.29e-05 ***
## factor(cigar)1   -16.500     17.349  -0.951   0.3424    
## factor(cigar)2    28.146     17.349   1.622   0.1059    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 208.2 on 279 degrees of freedom
## Multiple R-squared:  0.4922, Adjusted R-squared:  0.4776 
## F-statistic:  33.8 on 8 and 279 DF,  p-value: < 2.2e-16
# Sorting -----------------------------------------------------------------

ba.sort <- read.csv("sorting.csv", sep=";", dec=".", header=TRUE, row.names=1)
dat.sort <- ba.sort[,seq(3, ncol(ba.sort), by=3)]
res.fast <- fast(dat.sort, sep.words=";")
## Number of different words :  137
#********************************* END *************************************