R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

Including Plots

You can also embed plots, for example:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

# Install and load required packages
if (!requireNamespace("haven", quietly = TRUE)) install.packages("haven")
if (!requireNamespace("psych", quietly = TRUE)) install.packages(c("psych", "mnormt"))

library(haven)
library(psych)

mlm <- haven::read_sav("mlm(1).sav")

# Example of converting specific columns to numeric
mlm$NIGHTLEQ <- as.numeric(mlm$NIGHTLEQ)
mlm$LATENCY <- as.numeric(mlm$LATENCY)
mlm$ANNOY <- as.numeric(mlm$ANNOY)

# Handle missing values in LATENCY column
mlm$LATENCY[mlm$SUBNO %in% c("219", "323") & is.na(mlm$LATENCY)] <- c(1.22, 2.5)

# Descriptive statistics for selected columns
summary(mlm[, c("NIGHTLEQ", "LATENCY", "ANNOY", "AGE")])
##     NIGHTLEQ         LATENCY          ANNOY            AGE       
##  Min.   : 60.60   Min.   :1.000   Min.   :0.000   Min.   :19.00  
##  1st Qu.: 68.40   1st Qu.:1.000   1st Qu.:0.000   1st Qu.:31.00  
##  Median : 72.60   Median :1.000   Median :1.000   Median :56.00  
##  Mean   : 74.09   Mean   :1.765   Mean   :1.268   Mean   :49.67  
##  3rd Qu.: 78.20   3rd Qu.:2.000   3rd Qu.:2.000   3rd Qu.:63.00  
##  Max.   :111.50   Max.   :5.000   Max.   :5.000   Max.   :78.00
# Histograms
hist(mlm$NIGHTLEQ)

hist(mlm$LATENCY)

hist(mlm$ANNOY)

hist(mlm$AGE)

df <- mlm[, c("NIGHTLEQ", "LATENCY")]
df[] <- lapply(df, as.numeric)
df <- na.omit(df)  # Corrected line

cov_matrix <- cov(df)
D2 <- mahalanobis(na.omit(df), colMeans(na.omit(df)), cov_matrix)

qchisq(0.999, df = ncol(df))  # Critical value at alpha = 0.001
## [1] 13.81551
subset(D2, D2 >= qchisq(0.999, df = ncol(df)))
## [1] 16.49855 21.01684 23.41325
# Linear model
fit <- lm(ANNOY ~ NIGHTLEQ + LATENCY + AGE + SITE1 + SITE2, data = mlm)
library(olsrr)
## 
## Attaching package: 'olsrr'
## The following object is masked from 'package:datasets':
## 
##     rivers
ols_vif_tol(fit)
##   Variables Tolerance      VIF
## 1  NIGHTLEQ 0.8341250 1.198861
## 2   LATENCY 0.9692026 1.031776
## 3       AGE 0.8009259 1.248555
## 4     SITE1 0.8202965 1.219071
## 5     SITE2 0.7098953 1.408659
library(lme4)
## Loading required package: Matrix
# Example mixed-effects model
int_fit <- lmer(ANNOY ~ 1 + (1 | SUBNO) + (1 | HOUSE), REML = FALSE, data = mlm)
as.data.frame(VarCorr(int_fit))$vcov
## [1] 0.2860593 0.4114686 1.1209654
# Other mixed-effects model analyses
# ...