0% found this document useful (0 votes)
13 views2 pages

Linear Mixed Models in R Analysis

This document discusses linear mixed models used to analyze a dataset on dragons. It loads dragon data, explores the data distribution, and fits several linear models. It first fits basic linear models and plots diagnostics. It then adds mountain range as a fixed effect, finds it explains some variance. Finally, it fits a linear mixed model with mountain range and sampling site as random effects, explaining about 60% of the variance. Model diagnostics and predictions are plotted.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views2 pages

Linear Mixed Models in R Analysis

This document discusses linear mixed models used to analyze a dataset on dragons. It loads dragon data, explores the data distribution, and fits several linear models. It first fits basic linear models and plots diagnostics. It then adds mountain range as a fixed effect, finds it explains some variance. Finally, it fits a linear mixed model with mountain range and sampling site as random effects, explaining about 60% of the variance. Model diagnostics and predictions are plotted.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#modelos mixtos lineales#

setwd("C://Users//Biomas0//Desktop//CC-Linear-mixed-models-master")

load("[Link]")

head(dragons)

# seems close to a normal distribution - good!


hist(dragons$testScore)

#extrayendo la media y desviación estandar#


dragons$bodyLength2 <- scale(dragons$bodyLength, center = TRUE, scale = TRUE)

#modelo lineal#
[Link] <- lm(testScore ~ bodyLength2, data = dragons)
summary([Link])

# load the package containing both ggplot2 and dplyr


[Link]("tidyverse")

library(tidyverse)

(prelim_plot <- ggplot(dragons, aes(x = bodyLength, y = testScore)) +


geom_point() +
geom_smooth(method = "lm"))

#Trace los residuos: la línea roja debe ser casi plana#


plot([Link], which = 1)

#lo ideal es que los puntos caigan en la línea discontinua diagonal:#


plot([Link], which = 2)

#muestras de ocho cadenas montañosas#


boxplot(testScore ~ mountainRange, data = dragons)

#plotea misma linea de puntos pero se colorea las montañas#

(colour_plot <- ggplot(dragons, aes(x = bodyLength, y = testScore, colour =


mountainRange)) +
geom_point(size = 2) +
theme_classic() +
theme([Link] = "none"))

# create a facet for each mountain range

(split_plot <- ggplot(aes(bodyLength, testScore), data = dragons) +


geom_point() +
facet_wrap(~ mountainRange) +
xlab("length") +
ylab("test score"))

#ver el error de 1.2 mas grande que el stimate#


[Link] <- lm(testScore ~ bodyLength2 + mountainRange, data = dragons)
summary([Link])
#si se va agregar aleatorios por lo menos 5 factores# con pocos datos es muy
impreciso, no se puede tener confianza en los datos
[Link]("lme4")
library(lme4)

#incorporar un elemento aleatorioc1 y el nombre de la variable en este caso


(montañas)(1|variableName) #
[Link] <- lmer(testScore ~ bodyLength2 + (1|mountainRange), data = dragons)
summary([Link])

#varianza total del modelo, 339 es el total de 60% de la varianza despues del
modelo por las montañas#
#efecto fijo pendiente estimada y error #
339.7/(339.7 + 223.8) # ~60 %

#echar un vistazo a los cambios #


plot([Link])

# points fall nicely onto the line - good!


qqnorm(resid([Link]))
qqline(resid([Link]))

dragons <- within(dragons, sample <- factor(mountainRange:site))

#modelo correcto#
mixed.lmer2 <- lmer(testScore ~ bodyLength2 + (1|mountainRange) + (1|sample), data
= dragons)
summary(mixed.lmer2)

(mm_plot <- ggplot(dragons, aes(x = bodyLength, y = testScore, colour = site)) +


facet_wrap(~mountainRange, nrow=2) + # a panel for each mountain range
geom_point(alpha = 0.5) +
theme_classic() +
geom_line(data = cbind(dragons, pred = predict(mixed.lmer2)), aes(y = pred),
size = 1) + # adding predicted line from mixed model
theme([Link] = "none",
[Link] = unit(2, "lines")) # adding space between panels
)
#variable montaña fija#

[Link]("ggeffects")
library(ggeffects) # install the package first if you haven't already, then load it
# Extract the prediction data frame
[Link] <- ggpredict(mixed.lmer2, terms = c("bodyLength2")) # this gives overall
predictions for the model # Plot the predictions
(ggplot([Link]) + geom_line(aes(x = x, y = predicted)) + # slope
geom_ribbon(aes(x = x, ymin = predicted - [Link], ymax = predicted + [Link]),
fill = "lightgrey", alpha = 0.5) + # error band
geom_point(data = dragons, # adding the raw data (scaled values)
aes(x = bodyLength2, y = testScore, colour = mountainRange)) + labs(x = "Body
Length (indexed)", y = "Test Score", title = "Body length does not affect
intelligence in dragons") + theme_minimal() )

You might also like