simondp

Confidence intervals with Lme4

May 26th, 2020
1,987
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 2.31 KB | None | 0 0
  1. # Silly example revisited: How high do people jump after 1 and 2 cups of coffee?
  2.  
  3. ### Overall settings
  4. participants <- 10
  5. trialspercondition <- 10
  6.  
  7. ### Set parameters for each condition
  8. condition1m <- 50 # Mean Condition 1
  9. condition2m <- 60 # Mean Condition 2
  10. sd <- 10 # sd for both conditions
  11. indvar <- 0.1 # Individual differences
  12. trialerror <- 5 # How much noise to we have per trial?
  13.  
  14. ### Make dataframe with participants and condition
  15. sim <- matrix(NA,(participants*trialspercondition),3)
  16. sim2 <- matrix(NA,(participants*trialspercondition),3)
  17.  
  18. ### Loop over different conditions and participants
  19. k = 0 # This is for increasing each round, emulating trials
  20. for(i in 1:participants){
  21.  
  22.   #### Individual differences
  23.   indv <- rnorm(1, 1, indvar) #
  24.   for(j in 1:trialspercondition){
  25.     sim[j+k,1] <- i
  26.     sim[j+k,2] <- rnorm(1, condition1m*indv, sd) + rnorm(1,0,trialerror) # add little error
  27.     sim[j+k,3] <- 1
  28.     sim2[j+k,1] <- i
  29.     sim2[j+k,2] <- rnorm(1, condition2m*indv, sd) + rnorm(1,0,trialerror) # add little error
  30.     sim2[j+k,3] <- 2}
  31.   k = k+trialspercondition
  32. }
  33.  
  34. # Combine in data frame
  35. sims <- data.frame(rbind(sim,sim2))
  36. names(sims) <- c("Participant","Jump","Coffee")
  37. sims$Participant <- factor(sims$Participant)
  38. sims$Coffee <- factor(sims$Coffee)
  39. head(sims)
  40. summary(sims)
  41.  
  42. ### Load lme4 which is a great place to start for doing repeated analysis
  43. library(lme4)
  44.  
  45. # Make Null model
  46. m0 <- lmer(Jump~(1|Participant), data= sims)
  47. summary(m0)
  48.  
  49. # Make model with coffee
  50. m1 <- lmer(Jump~ - 1+ Coffee + (1|Participant), data= sims)
  51. summary(m1)
  52.  
  53. # Compare if a model with coffee is "worth the extra price" or a simpler model is preffered
  54. anova(m0,m1,refit=FALSE)
  55.  
  56. # Calculate confidence interval (SHOULD CONTAIN THE TRUE VALUES OF SIMULATION MOST OF THE TIME)
  57. ci95 <- confint(m1)
  58. round(c(summary(m1)$coefficients[1,1],ci95[3,1:2]),2)
  59. round(c(summary(m1)$coefficients[2,1],ci95[4,1:2]),2)
  60.  
  61. # Plot true vs captured
  62. plot(as.factor(1:2),c(condition1m,condition2m), pch=19,xlim=c(0,3), ylim=c(40,70), lwd=3,
  63.      main ="Comparing model to Truth", ylab="Height Jumped", xlab="Cups of Coffee") # TRUTH
  64. points(1:2,c(summary(m1)$coefficients[,1]), pch=19, col="red") # Model Estimate
  65. points(1:2,ci95[3:4,1], pch=6, col="red") # Lower
  66. points(1:2,ci95[3:4,2], pch=2, col="red") # Higher
Advertisement
Add Comment
Please, Sign In to add comment