# Part 1: load and explore the dataset ####
# The dataset is provided at http://dx.doi.org/10.1037/xlm0000677.supp
# The file you need is: "XLM-2018-0127_elp_data.txt"

# load the data by explicitly setting the path, or use "file.chose()"
# careful: use either of the two following commands, but if you use read.csv() specify the sep as below
data <- read.table("/home/martin/dataTeaching/enterSandman/XLM-2018-0127_elp_data.txt",header=T)
data <- read.csv("/home/martin/dataTeaching/enterSandman/XLM-2018-0127_elp_data.txt",header=T,sep=" ")

data <- read.csv("XLM-2018-0127_elp_data.txt",header=T,sep=" ")

# Don't forget to inspect the dataset: dim(),head(),tail(),str()
# You should have a dataframe with 1865 different compounds (cf. page 1876)

head(data)

### explanation of variables:
# simMO:  modifier relatedness      (similarity modifier - observed compound)
# simHO:  head relatedness          (similarity head - observed compound)
# simMC:  modifier composition      (similarity modifier - compositional compound)
# simHC:  head composition          (similarity head - compositional compound)
# simOC:  compound compositionality (similarity observed - compositional compound)
# mfreq:  modifier frequency
# hfreq:  head frequency
# cfreq:  compound frequency
# length: compound length
# RT:     lexical decision latencies
# The description of the variables is taken from the the second file,
# the r-script used to produce the models and graphs in the paper

# remember: we already know how to sort and order dataframes, and we can use the head/tail() commands to look at ordered dataframes.
head(data[order(data$simMO),c("word","simMO")])
head(data[order(data$simMO,decreasing=TRUE),c("word","simMO")])

# explicitly set "n"
head(data[order(data$simMO,decreasing=TRUE),c("word","simMO")],n=10)

# we install two additional packages to comfortably count items and investigate the correlational structure of a dataset.
# install.packages("plyr")
# install.packages("corrplot")
library(plyr)
library(corrplot)

# count how often the same items occur in the column "head"
count(data$head)

headFreqs <- count(data$head)
tail(headFreqs[order(headFreqs$freq),])

# test some correlations, just for fun
cor.test(data$simMO,data$cfreq)

# look at the correlations between all numerical variables in the dataset at the same time
corrplot(cor(data[,c(4:13)]))

# Part 2: Understanding regression and mixed-effects regression ####
# Note: this section simply tries to illustrate what linear regression aims to do and how to interpret the resulting models
# None of the following is something that you need to be able to do by yourself

# save the summary() of a simple regression model for use in plotting

cfreqModel <- summary(lm(RT ~ cfreq, data=data))
plot(data$cfreq,data$RT)
abline(cfreqModel)
plot(data$cfreq,data$RT)
abline(cfreqModel,lwd=5,col="yellow")



# The base model and what it tells us #####
# Now, we take a look at the base model, and try to understand what the residuals are

# load packages (these are needed to calculate the mixed effect regression models, and to test them for significance)
install.packages("lme4")
# install.packages("lmerTest")
library(lme4)
# library(lmerTest)
# The following baseline model is simply copied over from the entersandman-R-file
### baseline model                    
base <- lmer(log(RT)~1
             + cfreq+length+mfreq+hfreq
             + (1|mod) + (1|head), data=data)

summary(base)

# switch to non-scientific notation
options(scipen=999)

summary(base)

# extract the standardized residuals and save them in our dataset
data$resid <- scale(resid(base))
head(data[order(abs(data$resid)),c("word","resid")])

# showroom has the lowest residuals

tail(data[order(abs(data$resid)),c("word","resid")])

# limekiln has the highest residuals

# below: illustration of how to interpret the model summary (of the base model) by calculating the model prediction for "showroom"
data[data$word == "showroom",c("RT","cfreq","length","mfreq","hfreq")]
#          RT    cfreq length    mfreq    hfreq
# 1271 695.34 9.145162      8 14.57903 13.58177
log(data[data$word == "showroom",c("RT")])
# [1] 6.544401

# Using the regression formula to calculate the predicted value
6.966898 + (-0.037970 * 9.145162) + (0.022558 * 8) + (-0.010527 * 14.57903) + (-0.005867 * 13.58177)
# [1] 6.566963

# resulting value is still a bit off, lets add the adjustements to the intercept due to the random effects for "show" and "room" in their role as modifier and head.

randomEffectsSimple <- ranef(base, condVar=TRUE)

str(randomEffectsSimple)
modifier <- randomEffectsSimple[[1]]
head <- randomEffectsSimple[[2]]

modifier[row.names(modifier) == "show",]
# [1] -0.01983117

head[row.names(head) == "room",]
# [1] -0.002742753

6.966898 + (-0.01983117) + (-0.002742753)  + (-0.037970 * 9.145162) + (0.022558 * 8) + (-0.010527 * 14.57903) + (-0.005867 * 13.58177)
# [1] 6.544389

