|
| 1 | +## group lmPerm |
| 2 | + |
| 3 | +# based on http://www.utstat.toronto.edu/~brunner/workshops/mixed/NormalWithR.pdf#:~:text=Repeated%20measures%20analysis%20with%20R%20Summary%20for%20experienced,to%20the%20model%20for%20the%20random%20subject%20effect. |
| 4 | +# with information from https://stats.stackexchange.com/questions/7240/proportion-of-explained-variance-in-a-mixed-effects-model?rq=1 |
| 5 | + |
| 6 | + |
| 7 | + |
| 8 | +require(lme4) # |
| 9 | +require(car) # car also has vif function for multivariate models... |
| 10 | +require(MuMIn) |
| 11 | + |
| 12 | + |
| 13 | +group.lmer <- function(var.names, # should be character string |
| 14 | + in.data, |
| 15 | + dependent.var, #should be character string |
| 16 | + control.var = NULL, |
| 17 | + random.subject.effect = NULL # should be character string in the format |
| 18 | + # (1 | site) |
| 19 | + |
| 20 | +) { |
| 21 | + |
| 22 | + # Want to capture MSE, F, Pr(>F), estimate and standard error, AICc |
| 23 | + |
| 24 | + lmer.results <- data.frame(row.names = var.names, |
| 25 | + var.names = var.names, |
| 26 | + slope.estimate = rep(NA, times = length(var.names)), |
| 27 | + std.error = rep(NA), |
| 28 | + Mean.Sq = rep(NA), |
| 29 | + F.stat = rep(NA), |
| 30 | + prob.pval = rep(NA), |
| 31 | + adj.pval = rep(NA), |
| 32 | + AICc = rep(NA), |
| 33 | + AIC.REML = rep(NA), |
| 34 | + logLik = rep(NA) |
| 35 | + ) |
| 36 | + |
| 37 | + if (!is.null(control.var)) {control.var <- paste0(control.var, "+")} |
| 38 | + if (!is.null(random.subject.effect)) {random.subject.effect <- |
| 39 | + paste0("+ ", random.subject.effect)} |
| 40 | + |
| 41 | +i=1 |
| 42 | + for (i in 1:length(var.names)) { |
| 43 | + |
| 44 | + lmer.temp <- lmer(formula = as.formula(paste0(dependent.var, " ~ ", |
| 45 | + control.var, |
| 46 | + var.names[i], |
| 47 | + random.subject.effect |
| 48 | + )), |
| 49 | + data = in.data) |
| 50 | + cT.temp <- MuMIn::coefTable(lmer.temp) |
| 51 | + indx <- (2 + length(control.var)) |
| 52 | + |
| 53 | + # add calculated values to table: |
| 54 | + lmer.results$slope.estimate[i] <- cT.temp[indx, 1] |
| 55 | + lmer.results$std.error[i] <- cT.temp[indx, 2] |
| 56 | + |
| 57 | + lmer.results$Mean.Sq[i] <- anova(lmer.temp)[var.names[i],3] |
| 58 | + |
| 59 | + lmer.results$F.stat[i] <- car::Anova(lmer.temp, test = "F")[var.names[i],"F"] |
| 60 | + lmer.results$prob.pval[i] <- car::Anova(lmer.temp, test = "F")[var.names[i],"Pr(>F)"] |
| 61 | + |
| 62 | + |
| 63 | + lmer.results$AICc[i] <- AICc(lmer.temp)[1] # this is for the model... |
| 64 | + lmer.results$AIC.REML[i] <- lme4::llikAIC(lmer.temp)[[2]] |
| 65 | + lmer.results$logLik[i] <- lme4::llikAIC(lmer.temp)[[1]] |
| 66 | + |
| 67 | + } |
| 68 | + |
| 69 | + |
| 70 | +lmer.results$adj.pval <- p.adjust(p = lmer.results$prob.pval, method = "holm") |
| 71 | + |
| 72 | +return(lmer.results) |
| 73 | + |
| 74 | + |
| 75 | +} |
| 76 | + |
0 commit comments