# Linear regression models in R
# First step: we used a toy data frame with seven students and the points they achieved in 
# an intermediate exam and in the final exam
# It so happens that in this toy dataset every single student doubled their points from the intermediate exam in the final exam

newDataframe <- data.frame(names=c("Max","Maxi","John","Johnny","Fred","Freddy","Fritz"),gradesI=c(10,20,30,40,50,60,70),gradesF=c(20,40,60,80,100,120,140))


newDataframe

# Intuitively, we expect a perfect correlation
cor.test(newDataframe$gradesI,newDataframe$gradesF)

# Let us plot the data
plot(newDataframe$gradesI,newDataframe$gradesF)
lm(gradesF ~ gradesI,data=newDataframe)

# now we calculate a linear regression model and use the information from this model to plot a
# the line of best fit over our data.

ourModel <- lm(gradesF ~ gradesI,data=newDataframe)
ourModel
plot(newDataframe$gradesI,newDataframe$gradesF,xlim=c(-10,80),ylim=c(-10,150))
abline(ourModel,col="gold")
ourModel

# We then tried to understand in more detail what a regression model is trying to do, and how we can understand the values provided by a regression model
# linear regression
# Put very simply, a linear regression tries to model the relationship between two (or more) variables, in essence trying to predict the value of one on the basis of the other, that is, predicting a dependent variable based on an independent variable. 
# The basic model formula for our simple scenario is: 
# dependent variable = intercept + correlation coefficient * independent variable + error term 
# In our case:
summary(ourModel)
# 
# Call:
# lm(formula = gradesF ~ gradesI, data = newDataframe)
# 
# Residuals:
#          1          2          3          4          5          6          7 
#  9.278e-15 -1.453e-14  2.522e-15  1.164e-15  2.505e-16  2.890e-15 -1.576e-15 
# 
# Coefficients:
#               Estimate Std. Error    t value Pr(>|t|)    
# (Intercept) -2.148e-14  6.716e-15 -3.199e+00    0.024 *  
# gradesI      2.000e+00  1.502e-16  1.332e+16   <2e-16 ***
# ---
# Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# 
# Residual standard error: 7.947e-15 on 5 degrees of freedom
# Multiple R-squared:      1,	Adjusted R-squared:      1 
# F-statistic: 1.774e+32 on 1 and 5 DF,  p-value: < 2.2e-16
# 
# Warnmeldung:
# In summary.lm(ourModel) :
#   im Wesentlichen ein perfekter Fit: summary kann unzuverlässig sein

# Both the intercept (= the position on the y-axis where the regression line crosses the x-axis)
# as well as all error terms are zero, so for example for "Freddy" we have

newDataframe[newDataframe$name == "Freddy",]
#    names gradesI gradesF
# 6 Freddy      60     120

# dependent variable   = intercept + coefficient times independent variable + error term
# Freddy's final grade =     0       +      2        *        60              + 0

# OK, that works fine :)
# Second step: switch to our dataset with RTs and similarity ratings
ladec <- read.csv(file.choose())
# or, with named path and filename:
ladec <- read.csv(file="/home/martin/dataTeaching/mySuperSubset.csv")
dim(ladec)
str(ladec)

# Plot cosine similarity modifier to compound against reaction times
plot(ladec$simModCompound,ladec$elp_ld_rt)

# Remember: there is an extremely weak correlation
cor.test(ladec$simModCompound,ladec$elp_ld_rt)
str(cor.test(ladec$simModCompound,ladec$elp_ld_rt))
# we save the correlation coefficient for later re-use
corEffsimModCompoundRT <- cor.test(ladec$simModCompound,ladec$elp_ld_rt)$estimate

# a simple regression model: modeling the RTs based on the cosine similarity between modifier and compound
lm(elp_ld_rt ~ simModCompound,data=ladec)
simpleModel <- lm(elp_ld_rt ~ simModCompound,data=ladec)

plot(ladec$simModCompound,ladec$elp_ld_rt)
abline(simpleModel,col="gold",lwd=6)

# This model does have error terms, in fact, we see from visual inspection that it is 
# impossible to draw a straight line throught all the data points.
summary(simpleModel)
# 
# Call:
# lm(formula = elp_ld_rt ~ simModCompound, data = ladec)
# 
# Residuals:
#     Min      1Q  Median      3Q     Max 
# -237.40  -77.15  -18.16   55.14  811.99 
# 
# Coefficients:
#                Estimate Std. Error t value Pr(>|t|)    
# (Intercept)     788.927      5.895 133.836  < 2e-16 ***
# simModCompound  -43.561     13.842  -3.147  0.00167 ** 
# ---
# Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# 
# Residual standard error: 109 on 2096 degrees of freedom
# Multiple R-squared:  0.004703,	Adjusted R-squared:  0.004228 
# F-statistic: 9.903 on 1 and 2096 DF,  p-value: 0.001673


# We can add the error for each individual datapoint to our original dataset.
# They are called residuals, that is, values that are left over in the sense that they are not explained via the model prediction based on intercept and coefficient (the fixed effects)

ladec$resid <- simpleModel$residuals

# We can now check for individual datapoints what the model predicts in terms of fixed effects: 

# We can take any datapoint for illustration, here we use the compound "freewheel"

ladec[ladec$stim == "freewheel",c("stim","elp_ld_rt","simModCompound","resid")]
#           stim elp_ld_rt simModCompound     resid
# 1977 freewheel       760       0.155866 -22.13769

# For this compound, the model predicts the following reaction time:
789.959 + (-45.257) * 0.155866
# [1] 782.905

# We know from the dataset that the actual RT is 760
# The residual takes us there:

789.959 + (-45.257) * 0.155866 + (-22.90526)

# [1] 759.9997

# OK, there is a small rounding error, but fine :)

# Final bit: the correlation coefficient of the cor.test() is actually the root of the r.squared attribute of the model
summary(simpleModel)$r.squared
# [1] 0.004702675
rSquared <- summary(simpleModel)$r.squared

corEffsimModCompoundRT^2
#         cor 
# 0.004702675 

# In the summary, this is the "Multiple R-squared" bit, the adjusted r-squared value can be derived from this value and the overall number of independent variables and datapoints in the model.
# adjusted r2 = 1 - ((1-rSquared)*(nObs - 1)/(n-p-1))
# with nObs= number of observations
# and preds = number of independent variables
# HERE: preds = 1 (simModCompound)
#       nObs = 2098

preds <- 1
nObs <- 2098
1 - (((1-rSquared)*(nObs - 1))/(nObs-preds-1))
# [1] 0.004227819

summary(simpleModel)$adj.r.squared
# [1] 0.004227819

# We stopped here :)
