Introduction to Open Data Science - Course Project

This is overall view of the course updating weekly, so stay tuned.

About the project

Write a short description about the course and add a link to your GitHub repository here. This is an R Markdown (.Rmd) file so you should use R Markdown syntax.

# This is a so-called "R chunk" where you can write R code.

date()
## [1] "Mon Dec 13 09:22:37 2021"

HeyHeyHey, this is my course page. Hopefully this course will bring new knowledge to all the participants.

To whom it might concern, my GitHub repository can be found under the link down below:

GitHub/RetuWonData

Hope you find is as interesting as I do.

Cheers, Retu


Chapter 2: Simple regression and model validation

Describe the work you have done this week and summarize your learning.

I’ll do exactly whats mentioned above. First lets explore the data that we are dealing with. It is data related

learning <- read.csv("data/learning2014.csv",header = T)
str(learning)
## 'data.frame':    166 obs. of  7 variables:
##  $ gender  : chr  "F" "M" "F" "M" ...
##  $ age     : int  53 55 49 53 49 38 50 37 37 42 ...
##  $ attitude: num  3.7 3.1 2.5 3.5 3.7 3.8 3.5 2.9 3.8 2.1 ...
##  $ deep    : num  3.58 2.92 3.5 3.5 3.67 ...
##  $ stra    : num  3.38 2.75 3.62 3.12 3.62 ...
##  $ surf    : num  2.58 3.17 2.25 2.25 2.83 ...
##  $ points  : int  25 12 24 10 22 21 21 31 24 26 ...

Here you can see some structures of the data. As demonstrated, we have 166 observation containing 7 different variables. Gender is in this case binomial containing M (Male) and F (Female). Age (in years) is derived from the date of birth. Attitude describes global attitude toward statistics and it is the mean of several observation. Variables deep, stra and surf are describing the averages from different questions. The last variable points is the number of points from the exam.

Here is some figures showing some of the important findings from this study.

library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.0.5
# initialize plot with data and aesthetic mapping
ggplot(learning, aes(x = attitude, y = points, col = gender))+
  geom_point()+
  geom_smooth(method = "lm")+
  ggtitle("Student's points in function of attitude")
## `geom_smooth()` using formula 'y ~ x'
ggplot(learning, aes(x = age, y = points, col = gender))+
  geom_point()+
  geom_smooth(method = "lm")+
  ggtitle("Student's points in relation to age")
## `geom_smooth()` using formula 'y ~ x'

These two relationship shown above seems to be rather interesting. Surprisingly or not, if the attitude is better the learning outcome is better. Additionally, higher age correlates with lower learning outcome, especially for male. On the other hand plots below are not that interesting although they demonstrate the different between sex.

library(ggplot2)

# initialize plot with data and aesthetic mapping
ggplot(learning, aes(x = surf, y = points, col = gender))+
  geom_point()+
  geom_smooth(method = "lm")+
  ggtitle("Student's points in function of attitude")
## `geom_smooth()` using formula 'y ~ x'
ggplot(learning, aes(x = deep, y = points, col = gender))+
  geom_point()+
  geom_smooth(method = "lm")+
  ggtitle("Student's points in function of attitude")
## `geom_smooth()` using formula 'y ~ x'

And below we have numerical summary.

summary(learning)
##     gender               age           attitude          deep      
##  Length:166         Min.   :17.00   Min.   :1.400   Min.   :1.583  
##  Class :character   1st Qu.:21.00   1st Qu.:2.600   1st Qu.:3.333  
##  Mode  :character   Median :22.00   Median :3.200   Median :3.667  
##                     Mean   :25.51   Mean   :3.143   Mean   :3.680  
##                     3rd Qu.:27.00   3rd Qu.:3.700   3rd Qu.:4.083  
##                     Max.   :55.00   Max.   :5.000   Max.   :4.917  
##       stra            surf           points     
##  Min.   :1.250   Min.   :1.583   Min.   : 7.00  
##  1st Qu.:2.625   1st Qu.:2.417   1st Qu.:19.00  
##  Median :3.188   Median :2.833   Median :23.00  
##  Mean   :3.121   Mean   :2.787   Mean   :22.72  
##  3rd Qu.:3.625   3rd Qu.:3.167   3rd Qu.:27.75  
##  Max.   :5.000   Max.   :4.333   Max.   :33.00

People participating seems to be quite young and had good points overall.

Next we are going to evaluate the relationship of the variables with linear model.

my_model <- lm(points ~ gender+age+attitude+deep+stra+surf, data = learning)

# summary of the model
summary(my_model)
## 
## Call:
## lm(formula = points ~ gender + age + attitude + deep + stra + 
##     surf, data = learning)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -17.4506  -3.2479   0.3879   3.5243  11.4820 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 18.30246    5.25723   3.481 0.000644 ***
## genderM     -0.05858    0.92985  -0.063 0.949845    
## age         -0.09607    0.05396  -1.780 0.076929 .  
## attitude     3.44300    0.59776   5.760 4.24e-08 ***
## deep        -1.04279    0.78438  -1.329 0.185606    
## stra         0.95871    0.55150   1.738 0.084083 .  
## surf        -1.10891    0.84467  -1.313 0.191132    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.265 on 159 degrees of freedom
## Multiple R-squared:  0.2312, Adjusted R-squared:  0.2021 
## F-statistic: 7.967 on 6 and 159 DF,  p-value: 1.599e-07

After linear modeling and statistical testing, one can see that there is not so much difference. P value of the whole model is 1.599e-07, which means there is at least one variable effecting to points value.

T-test value probabilities Pr(>|t|) describe the change in dependent value after change in explanatory variable. The cut off for significance is typically alfa = 0.05. With this cutoff attitude is the only variable inducing significant changes so fitting new model with it.

my_model2 <- lm(points ~ attitude, data = learning)

# summary of the model
summary(my_model2)
## 
## Call:
## lm(formula = points ~ attitude, data = learning)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -16.9763  -3.2119   0.4339   4.1534  10.6645 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  11.6372     1.8303   6.358 1.95e-09 ***
## attitude      3.5255     0.5674   6.214 4.12e-09 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared:  0.1906, Adjusted R-squared:  0.1856 
## F-statistic: 38.61 on 1 and 164 DF,  p-value: 4.119e-09

In this model estimates are about 11.6 and 3.52 meaning that value of dependant variable is 11.6 when explanatory variable is x = 0. Estimate of attitude tells that dependant variable increase 3.52 ‘points’ when attitude increase by 1.

Multiple R-squared is 0.19 meaning that residuals are quite big and that this model is not nessesary the best for this data. To get better look of residuals several visualization can be done.

par(mar = c(4, 4, .1, .1))
# par(mfrow = c(2,2))
plot(my_model2, which = c(1,2,5))

Assumptions related to linear model are obviously linearity and that the distribution is normally distributed. The model follows normality assumption quite good as can be seen from QQ-plot. Furthermore, there is a constant variance in errors as can be seen in residual plot and non of the points have unusually high leverage to the model. As a sum up, the model describes the relationship between points and attitude quite good.

Back to top


Chapter 3: Logistic regression

Data

setwd("~/Tilastotiede/IODS-project")
alc <- read.csv(file = "data/alc.csv", row.names = 1)
dim(alc)
## [1] 370  51
colnames(alc)
##  [1] "school"     "sex"        "age"        "address"    "famsize"   
##  [6] "Pstatus"    "Medu"       "Fedu"       "Mjob"       "Fjob"      
## [11] "reason"     "guardian"   "traveltime" "studytime"  "schoolsup" 
## [16] "famsup"     "activities" "nursery"    "higher"     "internet"  
## [21] "romantic"   "famrel"     "freetime"   "goout"      "Dalc"      
## [26] "Walc"       "health"     "n"          "id.p"       "id.m"      
## [31] "failures"   "paid"       "absences"   "G1"         "G2"        
## [36] "G3"         "failures.p" "paid.p"     "absences.p" "G1.p"      
## [41] "G2.p"       "G3.p"       "failures.m" "paid.m"     "absences.m"
## [46] "G1.m"       "G2.m"       "G3.m"       "alc_use"    "high_use"  
## [51] "cid"

This data is from Portuguese secondary school and it describes the alcohol consumption habits. It was collected by using questionnaires and school reports. Here we have combined data set and they represent performing in Mathematics and Portuguese language.

More information can be found from here.

Hypothesis

If I have to guess Ill take these four variables that could explain high alcohol consumption. Below there is some thoughts why. goout - going out with friends (numeric: from 1 - very low to 5 - very high) - Typically if one is going out often alcohol may play some role. studytime - weekly study time (numeric: 1 - <2 hours, 2 - 2 to 5 hours, 3 - 5 to 10 hours, or 4 - >10 hours) - If one is studing more often the alcohol consumption is lover. G3 - final grade (numeric: from 0 to 20, output target) - Final grade is often good if one havent drink so much absences - number of school absences (numeric: from 0 to 93) - Typically people that are not often seen at school are more often seen at bar.

Back to top

Distribution and relationships

Here one can find correlation plot. I wanted to look hypothesized variables and some extras to see is there any better variables but not too many to keep plot easy to understand.

library(GGally)
## Warning: package 'GGally' was built under R version 4.0.5
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
ggcorr(alc[colnames(alc) %in% c("goout", "absences", "G3", "freetime", "studytime", "failures", "alc_use")],
       palette = "RdBu", label = TRUE, label_round=2)

Free time shows good correlation but I will keep the hypothesized variables as they all show good correlation.

As we are going to use binary variable high_use here are some box plot.

library(cowplot)
g1 <- ggplot(alc, aes(x = high_use, y = goout, col = sex)) +
  geom_boxplot()
g2 <- ggplot(alc, aes(x = high_use, y = studytime, col = sex)) +
  geom_boxplot()
g3 <- ggplot(alc, aes(x = high_use, y = G3, col = sex)) +
  geom_boxplot()
g4 <- ggplot(alc, aes(x = high_use, y = absences, col = sex)) +
  geom_boxplot()

plot_grid(g1,g2,g3,g4)

And here we can already somehow confirm some of the hypothesis as more out going increase the high alcohol use. If grades are lower especially for male the alcohol use is often higher and lastly some difference can be seen in absences. Contradictory, study time is not as good predictor as I thought it could be.

Back to top

Logistic regression

mod <- glm(high_use ~ goout + studytime + G3 + absences , data = alc)
summary(mod)
## 
## Call:
## glm(formula = high_use ~ goout + studytime + G3 + absences, data = alc)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -0.7931  -0.2933  -0.1333   0.3560   1.0605  
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  0.078876   0.116565   0.677 0.499045    
## goout        0.130941   0.019439   6.736 6.36e-11 ***
## studytime   -0.091461   0.025997  -3.518 0.000489 ***
## G3          -0.005319   0.006750  -0.788 0.431273    
## absences     0.013570   0.003981   3.409 0.000726 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for gaussian family taken to be 0.1719535)
## 
##     Null deviance: 77.700  on 369  degrees of freedom
## Residual deviance: 62.763  on 365  degrees of freedom
## AIC: 405.58
## 
## Number of Fisher Scoring iterations: 2
coef(mod)
##  (Intercept)        goout    studytime           G3     absences 
##  0.078876118  0.130941177 -0.091461304 -0.005318601  0.013569779
Odds <-coef(mod) %>% exp
Confidence <- confint(mod) %>% exp
## Waiting for profiling to be done...
cbind(Odds, Confidence)
##                  Odds     2.5 %    97.5 %
## (Intercept) 1.0820703 0.8610627 1.3598034
## goout       1.1399007 1.0972868 1.1841696
## studytime   0.9125966 0.8672614 0.9603018
## G3          0.9946955 0.9816217 1.0079434
## absences    1.0136623 1.0057837 1.0216026

Odds ratios tell basically how good predictors are the explanatory variables. If the value is higher than 1 variable predicts high use and if its smaller it predicts low use. In this case G3 is close to 1 and its confidence intervals are below and above 1 meaning that it is not good predictor. All the other predictor odds ratios and confidences are above (goout and absence) or below (studytime) 1. This gives the same interpretation as p-values from the statistical model.

Back to top

Prediction power

library(dplyr)
## Warning: package 'dplyr' was built under R version 4.0.5
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
mod <- glm(high_use ~ goout + studytime  + absences , data = alc)

#prediction and observing the data
prob <- predict(mod, type = "response")
alc <- mutate(alc, probability = prob)
alc <- mutate(alc, prediction = probability > 0.5)
select(alc, failures, absences, studytime, high_use, probability, prediction) %>% tail(10)
##     failures absences studytime high_use  probability prediction
## 361        1        7         1     TRUE  0.417707735      FALSE
## 362        0        3         1     TRUE  0.362542445      FALSE
## 363        0        2         1     TRUE  0.082861807      FALSE
## 364        0        4         2     TRUE  0.414546108      FALSE
## 365        0        3         1    FALSE  0.229597787      FALSE
## 366        0        4         1     TRUE  0.376333767      FALSE
## 367        0        0         3    FALSE -0.001240813      FALSE
## 368        1        4         1     TRUE  0.509278425       TRUE
## 369        2        8         2     TRUE  0.469711399      FALSE
## 370        1        0         1    FALSE  0.188223820      FALSE
table(high_use = alc$high_use, prediction = alc$prediction)
##         prediction
## high_use FALSE TRUE
##    FALSE   239   20
##    TRUE     68   43
g <- ggplot(alc, aes(x = probability, y = high_use, col = prediction))

# define the geom as points and draw the plot
g + geom_point()

# tabulate the target variable versus the predictions
table(high_use = alc$high_use, prediction = alc$prediction) %>% prop.table %>% addmargins
##         prediction
## high_use      FALSE       TRUE        Sum
##    FALSE 0.64594595 0.05405405 0.70000000
##    TRUE  0.18378378 0.11621622 0.30000000
##    Sum   0.82972973 0.17027027 1.00000000

According to these tests my three predictive variables are not enough to reliably predict high alcohol use. Fortunately, most of the predictions are right. The number table shows exactly the same thing as the proportion table. The model is predicting too much high alcohol users. From the tables one can read that 88/370. i.e. about 24% of the predicted variables are wrong.

Results are expected, as typically this complex data set is hard to predict. Against expectations the G3 variable (grades) was not good predictor and thus dropped out.

Back to top

Cross-validation

library(boot)
toCV <- function(class, prob) {
  n_wrong <- abs(class - prob) > 0.5
  mean(n_wrong)
}

toCV(class = alc$high_use, prob = alc$probability)
## [1] 0.2378378
cv <- cv.glm(data = alc, cost = toCV, glmfit = mod, K = 10)

# average number of wrong predictions in the cross validation
cv$delta[1]
## [1] 0.2432432

The number of wrong predictions is near 0.24, so very similar to simplified model evaluation.

Back to top


Chapter 4: Clustering and classification

Data

Loading the data and having some look of the main principles.

library(dplyr)
library(ggplot2)
library(tidyr)
## Warning: package 'tidyr' was built under R version 4.0.5
library(boot)
library(MASS)
## Warning: package 'MASS' was built under R version 4.0.5
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
library(corrplot)
## Warning: package 'corrplot' was built under R version 4.0.5
## corrplot 0.88 loaded
data(Boston)
head(Boston)
##      crim zn indus chas   nox    rm  age    dis rad tax ptratio  black lstat
## 1 0.00632 18  2.31    0 0.538 6.575 65.2 4.0900   1 296    15.3 396.90  4.98
## 2 0.02731  0  7.07    0 0.469 6.421 78.9 4.9671   2 242    17.8 396.90  9.14
## 3 0.02729  0  7.07    0 0.469 7.185 61.1 4.9671   2 242    17.8 392.83  4.03
## 4 0.03237  0  2.18    0 0.458 6.998 45.8 6.0622   3 222    18.7 394.63  2.94
## 5 0.06905  0  2.18    0 0.458 7.147 54.2 6.0622   3 222    18.7 396.90  5.33
## 6 0.02985  0  2.18    0 0.458 6.430 58.7 6.0622   3 222    18.7 394.12  5.21
##   medv
## 1 24.0
## 2 21.6
## 3 34.7
## 4 33.4
## 5 36.2
## 6 28.7
dim(Boston)
## [1] 506  14

This boston data set is contains 506 observations in 14 following variables:

crim = per capita crime rate by town.

zn = proportion of residential land zoned for lots over 25,000 sq.ft.

indus = proportion of non-retail business acres per town.

chas = Charles River dummy variable (= 1 if tract bounds river; 0 otherwise).

nox = nitrogen oxides concentration (parts per 10 million).

rm = average number of rooms per dwelling.

age = proportion of owner-occupied units built prior to 1940.

dis = weighted mean of distances to five Boston employment centres.

rad = index of accessibility to radial highways.

tax = full-value property-tax rate per $10,000.

ptratio = pupil-teacher ratio by town.

black = 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town.

lstat = lower status of the population (percent).

medv = median value of owner-occupied homes in $1000s.

Here is numerical and graphical abstract of the data.

summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08205   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00
cor_matrix <- cor(Boston) %>% round(digits = 2)
corrplot(cor_matrix, method="circle", type="upper", cl.pos="b", tl.pos="d", tl.cex = 0.6)

Visual overview show strong negative correlation between:

lower status of the population (percent) and median value of owner-occupied homes in $1000s proportion of owner-occupied units built prior to 1940 and weighted mean of distances to five Boston employment centres *proportion of non-retail business acres per town and weighted mean of distances to five Boston employment centres

These correlations make sense. For example, it is evident that buildings that are old are closer to employment centers.

Additionaly there are strong positive correlation between:

index of accessibility to radial highways and full-value property-tax rate per $10,000 proportion of non-retail business acres per town and nitrogen oxides concentration (parts per 10 million)

These correlations are also evident. The high way access indicate higher property tax rate and industry provide some NO emissions.

Back to top

Scaling

boston_scaled <- scale(Boston)
boston_scaled <- as.data.frame(boston_scaled)
summary(boston_scaled)
##       crim                 zn               indus              chas        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563   Min.   :-0.2723  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668   1st Qu.:-0.2723  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109   Median :-0.2723  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150   3rd Qu.:-0.2723  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202   Max.   : 3.6648  
##       nox                rm               age               dis         
##  Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331   Min.   :-1.2658  
##  1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366   1st Qu.:-0.8049  
##  Median :-0.1441   Median :-0.1084   Median : 0.3171   Median :-0.2790  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059   3rd Qu.: 0.6617  
##  Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164   Max.   : 3.9566  
##       rad               tax             ptratio            black        
##  Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047   Min.   :-3.9033  
##  1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876   1st Qu.: 0.2049  
##  Median :-0.5225   Median :-0.4642   Median : 0.2746   Median : 0.3808  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058   3rd Qu.: 0.4332  
##  Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372   Max.   : 0.4406  
##      lstat              medv        
##  Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 3.5453   Max.   : 2.9865

The mean is zero for all variables as they are divided by their means.

quant <- quantile(boston_scaled$crim)
crim <- cut(boston_scaled$crim, breaks = quant, include.lowest = TRUE, labels = c("low","med_low","med_high","high"))
boston_scaled <- dplyr::select(boston_scaled, -crim)
boston_scaled <- cbind(boston_scaled, crim)

# Creating training and testing sets
n <- nrow(boston_scaled)
ind <- sample(n,  size = n * 0.8)
training <- boston_scaled[ind,]
testing <- boston_scaled[-ind,]

Back to top

Fit the linear discriminant

ldamod <- lda(crim ~ ., data = training)
ldamod
## Call:
## lda(crim ~ ., data = training)
## 
## Prior probabilities of groups:
##       low   med_low  med_high      high 
## 0.2475248 0.2648515 0.2475248 0.2400990 
## 
## Group means:
##                   zn      indus        chas        nox          rm        age
## low       0.91527095 -0.9476595 -0.19358706 -0.8714022  0.41104265 -0.8653956
## med_low  -0.07670162 -0.2961420  0.02203357 -0.5672652 -0.10792599 -0.3074822
## med_high -0.37575963  0.1046333  0.20012296  0.3445439  0.08628542  0.4188837
## high     -0.48724019  1.0172187 -0.02879709  1.0643626 -0.47760368  0.8261800
##                 dis        rad        tax    ptratio       black      lstat
## low       0.8771171 -0.6947544 -0.7211892 -0.4903281  0.37840320 -0.7416633
## med_low   0.3560822 -0.5568311 -0.5160058 -0.0822023  0.32698082 -0.1197206
## med_high -0.3724509 -0.4156770 -0.3308301 -0.3115707  0.07194675 -0.0192637
## high     -0.8458720  1.6371072  1.5133254  0.7795879 -0.74380276  0.8940062
##                 medv
## low       0.49626422
## med_low   0.03291337
## med_high  0.19410389
## high     -0.71255308
## 
## Coefficients of linear discriminants:
##                  LD1          LD2         LD3
## zn       0.127759778  0.661293224 -0.83743803
## indus   -0.033161897 -0.179959599  0.60150423
## chas     0.002320892 -0.076447848  0.12257167
## nox      0.472232796 -0.709761507 -1.39516174
## rm       0.008805114 -0.005237364 -0.09099469
## age      0.259914463 -0.328985608 -0.11254669
## dis     -0.108515652 -0.157440775  0.24051697
## rad      3.072474971  0.949391606  0.19482115
## tax      0.062855797 -0.017542131  0.13851079
## ptratio  0.123024133  0.007883319 -0.19860162
## black   -0.118266847  0.057138339  0.15275994
## lstat    0.169876479 -0.226388518  0.48581600
## medv     0.057427661 -0.458141632 -0.06990642
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9519 0.0362 0.0119
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "blue", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

classes <- as.numeric(training$crim)

plot(ldamod, dimen = 2, col = classes, pch = classes)
lda.arrows(ldamod, myscale = 2)

There is a lot to understand in this figure for me. Apparently variable rad is important in this data.

Back to top

Class prediction

Removing the old data that are next predicted.

orig_class <- testing$crim
testing <- dplyr::select(testing, -crim)

Then the prediction itself.

pred <- predict(ldamod, newdata = testing)
table(correct = orig_class, predicted = pred$class)
##           predicted
## correct    low med_low med_high high
##   low       15      10        2    0
##   med_low    1      11        7    0
##   med_high   0       7       18    1
##   high       0       0        0   30

The prediction is pretty good for high and low but not so good especially for med_low group. Of course the training set and testing set are randomly assigned meaning that the result is changing every time it goes through. More validation is needed to have better evaluation.

Back to top

K-means

data('Boston')
boston_scaled2 <- scale(Boston)
boston_scaled2 <- as.data.frame(boston_scaled2)

# some distances
dist_eu <- dist(boston_scaled2)
summary(dist_eu)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.1343  3.4625  4.8241  4.9111  6.1863 14.3970

Plotting is not very efficient with all the variables so only plotting nox, rm, age, dis, rad and tax variables.

km <-kmeans(boston_scaled2, centers = 4)
pairs(boston_scaled2[,5:10], col = km$cluster)

Next trying to figure out best number of clusters.

set.seed(17)
k_max <- 10
twcss <- sapply(1:k_max, function(k){kmeans(boston_scaled2, k)$tot.withinss})
qplot(x = 1:k_max, y = twcss, geom = 'line') + theme_bw()

This exploration indicates that increasing number of clusters over 2 wont give dramatically better results. Therefor 2 clusters will give the best results.

km <-kmeans(Boston, centers = 2)
pairs(boston_scaled2[,6:10], col = km$cluster)

The best separation between groups can be found in variables tax (property tax-rate) and rad (distance to the radial highways).

All the variables were plotted at first but they didn’t provide any further information and only made figures harder to read so they are not shown.

Back to top


Chapter 5: Dimensionality reduction techniques

Overview of the data

human <- read.csv("data/human.csv", row.names = 1)
summary(human)
##    edu2_ratio       lab_ratio         Exp_Life        Exp_Educ    
##  Min.   :0.1717   Min.   :0.1857   Min.   :49.00   Min.   : 5.40  
##  1st Qu.:0.7264   1st Qu.:0.5984   1st Qu.:66.30   1st Qu.:11.25  
##  Median :0.9375   Median :0.7535   Median :74.20   Median :13.50  
##  Mean   :0.8529   Mean   :0.7074   Mean   :71.65   Mean   :13.18  
##  3rd Qu.:0.9968   3rd Qu.:0.8535   3rd Qu.:77.25   3rd Qu.:15.20  
##  Max.   :1.4967   Max.   :1.0380   Max.   :83.50   Max.   :20.20  
##       GNI           Mort_ratio          ABR              PRP       
##  Min.   :   581   Min.   :   1.0   Min.   :  0.60   Min.   : 0.00  
##  1st Qu.:  4198   1st Qu.:  11.5   1st Qu.: 12.65   1st Qu.:12.40  
##  Median : 12040   Median :  49.0   Median : 33.60   Median :19.30  
##  Mean   : 17628   Mean   : 149.1   Mean   : 47.16   Mean   :20.91  
##  3rd Qu.: 24512   3rd Qu.: 190.0   3rd Qu.: 71.95   3rd Qu.:27.95  
##  Max.   :123124   Max.   :1100.0   Max.   :204.80   Max.   :57.50

Here are the distribution plots.

Th variables in human data are definitely not normally distributed.

cor_matrix<-cor(human) %>% round(digits = 2)
cor_matrix
##            edu2_ratio lab_ratio Exp_Life Exp_Educ   GNI Mort_ratio   ABR   PRP
## edu2_ratio       1.00      0.01     0.58     0.59  0.43      -0.66 -0.53  0.08
## lab_ratio        0.01      1.00    -0.14     0.05 -0.02       0.24  0.12  0.25
## Exp_Life         0.58     -0.14     1.00     0.79  0.63      -0.86 -0.73  0.17
## Exp_Educ         0.59      0.05     0.79     1.00  0.62      -0.74 -0.70  0.21
## GNI              0.43     -0.02     0.63     0.62  1.00      -0.50 -0.56  0.09
## Mort_ratio      -0.66      0.24    -0.86    -0.74 -0.50       1.00  0.76 -0.09
## ABR             -0.53      0.12    -0.73    -0.70 -0.56       0.76  1.00 -0.07
## PRP              0.08      0.25     0.17     0.21  0.09      -0.09 -0.07  1.00
corrplot(cor_matrix, method="circle", type="lower", cl.pos="b", tl.pos="d", tl.cex = 0.6)

There is some clear positive and negative correlations. Negative correlation can be seen between life expectancy at birth and maternal mortality ratio (r =-0.86) plus expected years of schooling and maternal mortality ratio (r = -0.74). Additionally, there is positive correlation between Exp_Life and Exp_Educ (r = 0.79) plus Mort_ratio and ABR (r = 0.76).

Back to top

PCA with non standardized values

pca <- prcomp(human, center = F, scale. = F)
summa <- summary(pca)
pca_names <- round(100*summa$importance[2,], digits = 2)
biplot(pca, choices = 1:2, cex = c(0.6, 1), col = c("grey40", "deeppink2"),
       xlabs = c(1:nrow(human)), xlab = paste0("PC1 (", pca_names[1], "%)"),
       ylab = paste0("PC2 (", pca_names[2], "%)"),
       sub = "GNI explaine all the variation")
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

Results indicate that variable GNI explains all the variation in the data although it is most likely not true.

Back to top

PCA with non standardized values

pca <- prcomp(human, center = T, scale. = T)
summa <- summary(pca)
pca_names <- round(100*summa$importance[2,], digits = 2)
biplot(pca, choices = 1:2, cex = c(0.5, 1), col = c("grey40", "deeppink2"),
       #xlabs = c(1:nrow(human)),
       xlab = paste0("PC1 (", pca_names[1], "%)"),
       ylab = paste0("PC2 (", pca_names[2], "%)"),
       sub = "Now there is some variation")

As expected, result differ quite much between PCA with non standardized values and PCA with standardized values. Difference can be explained with mathematics. The PCA only understand standard deviation and scales and thus say that GNI with biggest scale and SD explains all the variance in the data. PCA does not have brains so it does not understand are variables having the same SD or scale.

Variables causing majority of variation are Exp_Educ, edu2_ratio, Exp_Life, Mort_ratio, and ABR.

Back to top

Personal interpretation

The second PCA shown here explains 69% of the variation in the data which is good number. PC1 covers 54 percentage of it. The first PC is inversely associated (PC is slower when variable is higher) with education and expected life span. Also, it is directly associated (PC is higher when variable is higher) with maternal mortal and adolescent birth rate. These finding can be found to be the opposite for each other as typically when the education is higher, the maternal mortality rate is lower.

PC2 explain about 16 percentage of variation in the data. It is directly associated with female participation in the society meaning the portion of labor force and percentage of females in the parliament. Basically, if PC2 value is high for some country it means that females are capable to affect to the society in country under consideration.

“lab_ratio” = Labo2.F / Labo2.M “PRP” = Percetange of female representatives in parliament

The second PC explained 16% of variation in the data. It associated positively with female participation in the society including proportions of females in the labor force and parliament. This PC indicates how well females are able to affect the society via working life and politics.

Back to top

MCA analysis

data("tea")
keep_columns <- c("Tea", "How", "how", "sugar", "where", "lunch")
tea_time <- dplyr::select(tea, one_of(keep_columns))
dim(tea_time)
## [1] 300   6
summary(tea_time)
##         Tea         How                      how           sugar    
##  black    : 74   alone:195   tea bag           :170   No.sugar:155  
##  Earl Grey:193   lemon: 33   tea bag+unpackaged: 94   sugar   :145  
##  green    : 33   milk : 63   unpackaged        : 36                 
##                  other:  9                                          
##                   where           lunch    
##  chain store         :192   lunch    : 44  
##  chain store+tea shop: 78   Not.lunch:256  
##  tea shop            : 30                  
## 
str(tea_time)
## 'data.frame':    300 obs. of  6 variables:
##  $ Tea  : Factor w/ 3 levels "black","Earl Grey",..: 1 1 2 2 2 2 2 1 2 1 ...
##  $ How  : Factor w/ 4 levels "alone","lemon",..: 1 3 1 1 1 1 1 3 3 1 ...
##  $ how  : Factor w/ 3 levels "tea bag","tea bag+unpackaged",..: 1 1 1 1 1 1 1 1 2 2 ...
##  $ sugar: Factor w/ 2 levels "No.sugar","sugar": 2 1 1 2 1 1 1 1 1 1 ...
##  $ where: Factor w/ 3 levels "chain store",..: 1 1 1 1 1 1 1 1 2 2 ...
##  $ lunch: Factor w/ 2 levels "lunch","Not.lunch": 2 2 2 2 2 2 2 2 2 2 ...
gather(tea_time) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free") + geom_bar() + theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 8))
## Warning: attributes are not identical across measure variables;
## they will be dropped

mca <- MCA(tea_time, graph = FALSE)
summary(mca)
## 
## Call:
## MCA(X = tea_time, graph = FALSE) 
## 
## 
## Eigenvalues
##                        Dim.1   Dim.2   Dim.3   Dim.4   Dim.5   Dim.6   Dim.7
## Variance               0.279   0.261   0.219   0.189   0.177   0.156   0.144
## % of var.             15.238  14.232  11.964  10.333   9.667   8.519   7.841
## Cumulative % of var.  15.238  29.471  41.435  51.768  61.434  69.953  77.794
##                        Dim.8   Dim.9  Dim.10  Dim.11
## Variance               0.141   0.117   0.087   0.062
## % of var.              7.705   6.392   4.724   3.385
## Cumulative % of var.  85.500  91.891  96.615 100.000
## 
## Individuals (the 10 first)
##                       Dim.1    ctr   cos2    Dim.2    ctr   cos2    Dim.3
## 1                  | -0.298  0.106  0.086 | -0.328  0.137  0.105 | -0.327
## 2                  | -0.237  0.067  0.036 | -0.136  0.024  0.012 | -0.695
## 3                  | -0.369  0.162  0.231 | -0.300  0.115  0.153 | -0.202
## 4                  | -0.530  0.335  0.460 | -0.318  0.129  0.166 |  0.211
## 5                  | -0.369  0.162  0.231 | -0.300  0.115  0.153 | -0.202
## 6                  | -0.369  0.162  0.231 | -0.300  0.115  0.153 | -0.202
## 7                  | -0.369  0.162  0.231 | -0.300  0.115  0.153 | -0.202
## 8                  | -0.237  0.067  0.036 | -0.136  0.024  0.012 | -0.695
## 9                  |  0.143  0.024  0.012 |  0.871  0.969  0.435 | -0.067
## 10                 |  0.476  0.271  0.140 |  0.687  0.604  0.291 | -0.650
##                       ctr   cos2  
## 1                   0.163  0.104 |
## 2                   0.735  0.314 |
## 3                   0.062  0.069 |
## 4                   0.068  0.073 |
## 5                   0.062  0.069 |
## 6                   0.062  0.069 |
## 7                   0.062  0.069 |
## 8                   0.735  0.314 |
## 9                   0.007  0.003 |
## 10                  0.643  0.261 |
## 
## Categories (the 10 first)
##                        Dim.1     ctr    cos2  v.test     Dim.2     ctr    cos2
## black              |   0.473   3.288   0.073   4.677 |   0.094   0.139   0.003
## Earl Grey          |  -0.264   2.680   0.126  -6.137 |   0.123   0.626   0.027
## green              |   0.486   1.547   0.029   2.952 |  -0.933   6.111   0.107
## alone              |  -0.018   0.012   0.001  -0.418 |  -0.262   2.841   0.127
## lemon              |   0.669   2.938   0.055   4.068 |   0.531   1.979   0.035
## milk               |  -0.337   1.420   0.030  -3.002 |   0.272   0.990   0.020
## other              |   0.288   0.148   0.003   0.876 |   1.820   6.347   0.102
## tea bag            |  -0.608  12.499   0.483 -12.023 |  -0.351   4.459   0.161
## tea bag+unpackaged |   0.350   2.289   0.056   4.088 |   1.024  20.968   0.478
## unpackaged         |   1.958  27.432   0.523  12.499 |  -1.015   7.898   0.141
##                     v.test     Dim.3     ctr    cos2  v.test  
## black                0.929 |  -1.081  21.888   0.382 -10.692 |
## Earl Grey            2.867 |   0.433   9.160   0.338  10.053 |
## green               -5.669 |  -0.108   0.098   0.001  -0.659 |
## alone               -6.164 |  -0.113   0.627   0.024  -2.655 |
## lemon                3.226 |   1.329  14.771   0.218   8.081 |
## milk                 2.422 |   0.013   0.003   0.000   0.116 |
## other                5.534 |  -2.524  14.526   0.197  -7.676 |
## tea bag             -6.941 |  -0.065   0.183   0.006  -1.287 |
## tea bag+unpackaged  11.956 |   0.019   0.009   0.000   0.226 |
## unpackaged          -6.482 |   0.257   0.602   0.009   1.640 |
## 
## Categorical variables (eta2)
##                      Dim.1 Dim.2 Dim.3  
## Tea                | 0.126 0.108 0.410 |
## How                | 0.076 0.190 0.394 |
## how                | 0.708 0.522 0.010 |
## sugar              | 0.065 0.001 0.336 |
## where              | 0.702 0.681 0.055 |
## lunch              | 0.000 0.064 0.111 |
fviz_screeplot(mca, addlabels = TRUE, ylim = c(0, 20))

plot(mca, invisible=c("ind"), habillage = "quali", graph.type = "classic")

This MCA is trying to explain six variables related to tea drinking. The data contains 300 observations. Plots shown above demonstrate that the first few dimensions explain high number of variation in the data. First two plotted to MCA map are capable to explain almost 30 percentage of variation. In this plot the distance between points describe the relationship between variables. For example, variables “how” and “where” are popping up together in the plot meaning they are somehow similar. Same observation can be obtained from histograms and it is definitely the main finding from selected variables.

Back to top


Chapter 6: Analysis of longitudinal data

This week data under investigation is longitudinal. Two different data sets will be analyzed.

Rats

The first data set describes rats and their nutrition. Data contains two groups few measurement points and weight.

library(dplyr)
library(ggplot2)
library(GGally)
library(tidyr)
library(lme4)
## Warning: package 'lme4' was built under R version 4.0.5
## Loading required package: Matrix
## 
## Attaching package: 'Matrix'
## The following objects are masked from 'package:tidyr':
## 
##     expand, pack, unpack
RATSL <- read.csv("data/Rats_longitudinal.csv", row.names = 1)
str(RATSL)
## 'data.frame':    176 obs. of  5 variables:
##  $ ID    : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ Group : int  1 1 1 1 1 1 1 1 2 2 ...
##  $ WD    : chr  "WD1" "WD1" "WD1" "WD1" ...
##  $ Weight: int  240 225 245 260 255 260 275 245 410 405 ...
##  $ Time  : int  1 1 1 1 1 1 1 1 1 1 ...
RATSL$ID <- factor(RATSL$ID)
RATSL$Group <- factor(RATSL$Group)
summary(RATSL)
##        ID      Group       WD                Weight           Time      
##  1      : 11   1:88   Length:176         Min.   :225.0   Min.   : 1.00  
##  2      : 11   2:44   Class :character   1st Qu.:267.0   1st Qu.:15.00  
##  3      : 11   3:44   Mode  :character   Median :344.5   Median :36.00  
##  4      : 11                             Mean   :384.5   Mean   :33.55  
##  5      : 11                             3rd Qu.:511.2   3rd Qu.:50.00  
##  6      : 11                             Max.   :628.0   Max.   :64.00  
##  (Other):110
ggplot(RATSL, aes(x = Time, y = Weight, linetype = ID)) +
  geom_line() + 
  scale_linetype_manual(values = rep(1:10, times=4)) +
  facet_grid(. ~ Group, labeller = label_both) +
  scale_x_continuous(name = "Time", breaks = seq(0, 60, 10)) + 
  scale_y_continuous(name = "Weight") + 
  theme(legend.position = "none")

First illustration of the data already show the difference between groups. Additionally, on mouse in group 2 is very heavy compared to others.

Back to top

Next we will have a look of standardized.

RATSL <- RATSL %>%
  group_by(Time) %>%
  mutate(stdweight = (Weight - mean(Weight))/ sd(Weight)) %>%
  ungroup()

ggplot(RATSL, aes(x = Time, y = stdweight, linetype = ID)) +
  geom_line() + 
  scale_linetype_manual(values = rep(1:10, times=4)) +
  facet_grid(. ~ Group, labeller = label_both) +
  scale_x_continuous(name = "Time", breaks = seq(0, 60, 10)) + 
  scale_y_continuous(name = "STD weight") + 
  theme(legend.position = "none")

As expected, the growing trend is disappearing.

Next up graphical summary.

n <- RATSL$Time %>% unique() %>% length()
RAT_sum <- RATSL %>%
  group_by(Time, Group) %>%
  summarise( mean = mean(Weight), se = sd(Weight)/sqrt(n) ) %>%
  ungroup()
glimpse(RAT_sum)
## Rows: 1
## Columns: 2
## $ mean <dbl> 384.483
## $ se   <dbl> 38.34032

Back to top

# ggplot(RAT_sum, aes(x = Time, y = mean, linetype = Group, shape = Group)) +
#   geom_line() +
#   scale_linetype_manual(values = c(1,2,3)) +
#   geom_point(size=3) +
#   scale_shape_manual(values = c(1,2,3)) +
#   geom_errorbar(aes(ymin=mean-se, ymax=mean+se, linetype="1"), width=0.3) +
#   theme(legend.position = c(0.9,0.4)) +
#   scale_x_continuous(name = "Time", breaks = seq(0, 60, 10)) +
#   scale_y_continuous(name = "mean weight +/- error")

Graph shows clear difference between groups. To conclude this box plot illustration is used.

# RAT_sum2 <- RATSL %>%
#   filter(Time > 1) %>%
#   group_by(Group, ID) %>%
#   summarise( mean=mean(Weight) ) %>%
#   ungroup()
# glimpse(RAT_sum2)
# ggplot(RAT_sum2, aes(x = Group, y = mean)) +
#   geom_boxplot() +
#   stat_summary(fun.y = "mean", geom = "point", shape=11, size=4, fill = "white") +
#   scale_y_continuous(name = "mean weight at the end")

One of the means in group 2 is much higher compared to outhers so this will be dropped as an outlier.

# RAT_sum2 <- RAT_sum2 %>% filter(mean < 570)
# 
# ggplot(RAT_sum2, aes(x = Group, y = mean)) +
#   geom_boxplot() +
#   stat_summary(fun.y = "mean", geom = "point", shape=11, size=4, fill = "white") +
#   scale_y_continuous(name = "mean weight at the end")

And now the means look better! To further conclude the the significance between the groups linear regression analysis will be made.

# RATS <- read.table("https://raw.githubusercontent.com/KimmoVehkalahti/MABS/master/Examples/data/rats.txt", sep  ="\t", header = T)
# RATS <- RATS[c(-12),]
# RAT_sum2 <- RAT_sum2 %>%
#   mutate(baseline = RATS$WD1)
# 
# mod <- lm(mean ~ baseline + Group, data = RAT_sum2)
# anova(mod)

Results demonstrate that there is major difference between mice groups. P-value between group values is 0.0037, well above alfa 0.05. Without removing the one outlier p-value remains 0.076 that is not significant. This demonstrate that preprosessing is a critical part of data analysis.

Back to top

Bprs

Next longitudinal Bprs data will be analyzed. This data represents 40 male subjects that were receiving different treatment for eight weeks during which they were rated on brief psychiatric rating scale (BPRS). It is used to evaluate the level of schizophrenia.

First of all some summaries of the data.

BPRSL <- read.csv("data/Bprsl_longitudinal.csv", header = TRUE)
BPRSL$treatment <- factor(BPRSL$treatment)
BPRSL$subject <- factor(BPRSL$subject)
str(BPRSL)
## 'data.frame':    360 obs. of  6 variables:
##  $ X        : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ treatment: Factor w/ 2 levels "1","2": 1 1 1 1 1 1 1 1 1 1 ...
##  $ subject  : Factor w/ 20 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
##  $ weeks    : chr  "week0" "week0" "week0" "week0" ...
##  $ bprs     : int  42 58 54 55 72 48 71 30 41 57 ...
##  $ week     : int  0 0 0 0 0 0 0 0 0 0 ...
ggplot(BPRSL, aes(x = week, y = bprs, linetype = subject)) +
  geom_line() +
  scale_linetype_manual(values = rep(1:10, times=4)) +
  facet_grid(. ~ treatment, labeller = label_both) +
  theme(legend.position = "none") + 
  scale_y_continuous(limits = c(min(BPRSL$bprs), max(BPRSL$bprs)))

Data seem to have quite big variance. With gentle estimation somobody would say that there is decreasing trend but lets analyze the data first.

Back to top

Linear mixed model to data.

regmod <- lm(bprs ~ week + treatment, data = BPRSL)
summary(regmod)
## 
## Call:
## lm(formula = bprs ~ week + treatment, data = BPRSL)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -22.454  -8.965  -3.196   7.002  50.244 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  46.4539     1.3670  33.982   <2e-16 ***
## week         -2.2704     0.2524  -8.995   <2e-16 ***
## treatment2    0.5722     1.3034   0.439    0.661    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 12.37 on 357 degrees of freedom
## Multiple R-squared:  0.1851, Adjusted R-squared:  0.1806 
## F-statistic: 40.55 on 2 and 357 DF,  p-value: < 2.2e-16

This model don’t understand that the data is repeated so it can not be trusted really. Instead random intercept model could be better suited.

library(lme4)
refmod <- lmer(bprs ~ week + treatment + (1 | subject), data = BPRSL, REML = FALSE)
summary(refmod)
## Linear mixed model fit by maximum likelihood  ['lmerMod']
## Formula: bprs ~ week + treatment + (1 | subject)
##    Data: BPRSL
## 
##      AIC      BIC   logLik deviance df.resid 
##   2748.7   2768.1  -1369.4   2738.7      355 
## 
## Scaled residuals: 
##     Min      1Q  Median      3Q     Max 
## -3.0481 -0.6749 -0.1361  0.4813  3.4855 
## 
## Random effects:
##  Groups   Name        Variance Std.Dev.
##  subject  (Intercept)  47.41    6.885  
##  Residual             104.21   10.208  
## Number of obs: 360, groups:  subject, 20
## 
## Fixed effects:
##             Estimate Std. Error t value
## (Intercept)  46.4539     1.9090  24.334
## week         -2.2704     0.2084 -10.896
## treatment2    0.5722     1.0761   0.532
## 
## Correlation of Fixed Effects:
##            (Intr) week  
## week       -0.437       
## treatment2 -0.282  0.000

This model now gives more suitable results as for example standard error for week is now smaller. Still this model doesn’t show optimal fit. To get even better fit for this kind of real life data both random intercept and random slope are used.

refmod2 <- lmer(bprs ~ week + treatment + (week | subject), data = BPRSL, REML = FALSE)
summary(refmod2)
## Linear mixed model fit by maximum likelihood  ['lmerMod']
## Formula: bprs ~ week + treatment + (week | subject)
##    Data: BPRSL
## 
##      AIC      BIC   logLik deviance df.resid 
##   2745.4   2772.6  -1365.7   2731.4      353 
## 
## Scaled residuals: 
##     Min      1Q  Median      3Q     Max 
## -2.8919 -0.6194 -0.0691  0.5531  3.7976 
## 
## Random effects:
##  Groups   Name        Variance Std.Dev. Corr 
##  subject  (Intercept) 64.8222  8.0512        
##           week         0.9609  0.9802   -0.51
##  Residual             97.4305  9.8707        
## Number of obs: 360, groups:  subject, 20
## 
## Fixed effects:
##             Estimate Std. Error t value
## (Intercept)  46.4539     2.1052  22.066
## week         -2.2704     0.2977  -7.626
## treatment2    0.5722     1.0405   0.550
## 
## Correlation of Fixed Effects:
##            (Intr) week  
## week       -0.582       
## treatment2 -0.247  0.000
anova(refmod, refmod2)
## Data: BPRSL
## Models:
## refmod: bprs ~ week + treatment + (1 | subject)
## refmod2: bprs ~ week + treatment + (week | subject)
##         npar    AIC    BIC  logLik deviance  Chisq Df Pr(>Chisq)  
## refmod     5 2748.7 2768.1 -1369.4   2738.7                       
## refmod2    7 2745.4 2772.6 -1365.7   2731.4 7.2721  2    0.02636 *
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Now the t value for treatment2 in refmod2 is looking extremely low already. Additionally, chi-squared p-value is low, 0.026 meaning thet tre refmod2 model is better describing this data. Still one more option with interactions between treatments to go.

refmod3 <- lmer(bprs ~ week * treatment + (week | treatment), data = BPRSL, REML = FALSE)
## boundary (singular) fit: see ?isSingular
summary(refmod3)
## Linear mixed model fit by maximum likelihood  ['lmerMod']
## Formula: bprs ~ week * treatment + (week | treatment)
##    Data: BPRSL
## 
##      AIC      BIC   logLik deviance df.resid 
##   2843.3   2874.4  -1413.7   2827.3      352 
## 
## Scaled residuals: 
##     Min      1Q  Median      3Q     Max 
## -1.9453 -0.7547 -0.2281  0.5304  4.1794 
## 
## Random effects:
##  Groups    Name        Variance  Std.Dev.  Corr 
##  treatment (Intercept) 2.571e-07 5.071e-04      
##            week        6.318e-09 7.948e-05 -1.00
##  Residual              1.508e+02 1.228e+01      
## Number of obs: 360, groups:  treatment, 2
## 
## Fixed effects:
##                 Estimate Std. Error t value
## (Intercept)      47.8856     1.6876  28.376
## week             -2.6283     0.3545  -7.415
## treatment2       -2.2911     2.3866  -0.960
## week:treatment2   0.7158     0.5013   1.428
## 
## Correlation of Fixed Effects:
##             (Intr) week   trtmn2
## week        -0.840              
## treatment2  -0.707  0.594       
## wek:trtmnt2  0.594 -0.707 -0.840
## optimizer (nloptwrap) convergence code: 0 (OK)
## boundary (singular) fit: see ?isSingular
anova(refmod2, refmod3)
## Data: BPRSL
## Models:
## refmod2: bprs ~ week + treatment + (week | subject)
## refmod3: bprs ~ week * treatment + (week | treatment)
##         npar    AIC    BIC  logLik deviance Chisq Df Pr(>Chisq)
## refmod2    7 2745.4 2772.6 -1365.7   2731.4                    
## refmod3    8 2843.3 2874.4 -1413.7   2827.3     0  1          1

Unfortunately this option is not making model any better. As modle evaluation tells, chi-squared p-value is 1, meaning that there is no use for this model with this data.

As said lets continue with previous model. Here is some visual comparison of the real observation and the data from the model.

ggplot(BPRSL, aes(x = week, y = bprs, linetype = subject)) +
  geom_line() +
  scale_x_continuous(name = "Weeks") +
  scale_y_continuous(name = "BPRS") +
  theme(legend.position = "none") +
  scale_linetype_manual(values = rep(1:10, times=4)) +
  facet_grid(. ~ treatment, labeller = label_both)

Fitted <- fitted(refmod2)
BPRSL <- BPRSL %>% mutate(fitted = Fitted)

ggplot(BPRSL, aes(x = week, y = Fitted, linetype = subject)) +
  geom_line() +
  scale_x_continuous(name = "Weeks") +
  scale_y_continuous(name = "Fitted BPRS") +
  theme(legend.position = "none") +
  scale_linetype_manual(values = rep(1:10, times=4)) +
  facet_grid(. ~ treatment, labeller = label_both)

The lines are showing similar kind of changes that can be seen in the real data. This is defenately better model than the first one, as it doesn’t allow slope randomness meaning that all the lines are parallel. Also, third model dont cahnge a thing compared to this second one. Always need to remember that this is just a model, and that exact fit is impossible to get.

Thanks for the grat course!!

Back to top