simulations.Rmd 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. ---
  2. title: "Simulation test"
  3. output: html_document
  4. ---
  5. ```{r setup, include=FALSE}
  6. knitr::opts_chunk$set(echo = TRUE)
  7. library(simstudy)
  8. library(lme4)
  9. library("performance") # ICC
  10. library(ggplot2)
  11. RECALC=TRUE
  12. data_sets = c('aclew', 'lena')
  13. check_small_var<-function(x,y,i) round(x[i],3)==round(y[i],3) & round(y[i],3) == 0
  14. fit_child_model<-function(dataframe, metric){
  15. # Fit formula where experiment is removed
  16. formula <- as.formula(paste0(metric, "~ (1|child_id)")) #removed age_s +
  17. model <- lmer(formula, data=dataframe)
  18. return (model)
  19. }
  20. extract_chi_variables<-function(model){
  21. icc.result.mixed <- c(icc(model)$ICC_adjusted,icc(model)$ICC_conditional)
  22. icc.result.split <- c(as.data.frame(icc(model, by_group=TRUE))$ICC, NA)
  23. ranefs_vars <- t(as.data.frame(VarCorr(model))["vcov"])
  24. ranefs_stdv <- t(as.data.frame(VarCorr(model))["sdcor"])
  25. # chi, NA, residual
  26. ranefs_vars <-c(ranefs_vars[1],NA,ranefs_vars[2])
  27. ranefs_stdv <-c(ranefs_stdv[1],NA,ranefs_stdv[2])
  28. # chi, NA
  29. ns<-c(unlist(summary(model)$n),NA)
  30. return (c(#coefficients(summary(model))["age_s",],
  31. icc.result.mixed,
  32. icc.result.split,
  33. ranefs_vars,
  34. ranefs_stdv,
  35. nobs(model),ns))
  36. }
  37. extract_full_variables<-function(model){
  38. icc.result.mixed <- c(icc(model)$ICC_adjusted,icc(model)$ICC_conditional)
  39. icc.result.split <- t(as.data.frame(icc(model, by_group=TRUE))$ICC)
  40. ranefs_vars <- t(as.data.frame(VarCorr(model))["vcov"])
  41. ranefs_stdv <- t(as.data.frame(VarCorr(model))["sdcor"])
  42. ns<-t(data.frame(summary(model)$n))
  43. return (c( # coefficients(summary(model))["age_s",],
  44. icc.result.mixed,
  45. icc.result.split,
  46. ranefs_vars,
  47. ranefs_stdv,
  48. nobs(model),ns))
  49. }
  50. new_fit_models<-function(dataframe, data_set, metric, fit_full = TRUE){ #age,
  51. iqr = quantile(dataframe[,metric],.75,na.rm=T)-quantile(dataframe[,metric],.25,na.rm=T)
  52. if(fit_full){
  53. # Fit full model
  54. formula <- as.formula(paste0(metric, "~ (1|experiment/child_id)")) #removed age_s +
  55. model <- lmer(formula, data=dataframe)
  56. }
  57. if(fit_full & !isSingular(model)) # Fitted full model
  58. {
  59. form="full"
  60. sw=shapiro.test(resid(model))$p
  61. mod_variables <- extract_full_variables(model)
  62. # Build line
  63. } else {
  64. model <- fit_child_model(dataframe, metric)
  65. if(!isSingular(model)){
  66. form = "no_exp"
  67. sw=shapiro.test(resid(model))$p
  68. mod_variables <- extract_chi_variables(model)
  69. } else {
  70. form='no_chi_effect'
  71. sw = NA
  72. mod_variables = c(
  73. # NA,NA,NA, # c(coefficients(summary(model))["age_s",]
  74. NA,NA, # icc.result.mixed
  75. NA,NA, # icc.result.split
  76. NA,NA,NA, # ranefs_vars
  77. NA,NA,NA, # raners_std
  78. NA,NA,NA) # nobs (child, corpus), nobs
  79. }
  80. }
  81. icc.row = c(data_set, metric, iqr, mod_variables, form, sw) #age,
  82. return (icc.row)
  83. }
  84. ```
  85. ## Assumptions behind the simulation
  86. We will inform the simulation by the data we have as follows:
  87. - we'll have the same N of corpora, and of children in each corpus
  88. - we'll have the same variables for each -- and these variables will have the same mean & SD for day 1 of recordings as in observed data
  89. We'll depart from reality as follows:
  90. - we will not consider the r across multiple days observed in the data, but instead generate data points to vary r from a small correlation (r=.1), a moderate one (r=.3), and a larger one (r=.5) -- higher values of r do not seem reasonable given what we know about infant measures
  91. - we will not consider child age, nor variable re-recording periods
  92. - we will have a single pair of recordings (rather than variable N of re-recordings)
  93. ## Implementation approach
  94. We use simstudy, a package created for such simulations, following the vignette https://cran.r-project.org/web/packages/simstudy/vignettes/correlated.html to create correlated data providing a correlation matrix
  95. ```{r extract-parameters, eval=RECALC}
  96. # Columns that should not be scaled or taken into account as metrics
  97. no.scale.columns <- c('experiment', 'session_id', 'child_id','child_id_unique','age_s',
  98. 'date_iso', 'child_dob', 'missing_audio',"age_bin","duration","usession_id",
  99. "normative","age","duration_alice", "duration_vcm" , "duration_vtc","duration_its" )
  100. #create matrix to hold info in
  101. df.vars.cols = c("data_set","experiment","n","metric", "mean","sd")
  102. df.vars = data.frame(matrix(ncol=length(df.vars.cols),nrow=0, dimnames=list(NULL, df.vars.cols)), stringsAsFactors=FALSE)
  103. for (data_set in data_sets){ # data_set = "aclew"
  104. mydat <- read.csv(paste0('../data_output/', data_set,'_metrics_scaled.csv')) # TO DISCUSS: scaled or unscaled?
  105. metrics = colnames(mydat)[!is.element(colnames(mydat), no.scale.columns)]
  106. #select down to first recording by child
  107. mydat$uchild_id=paste(mydat$experiment,mydat$child_id)
  108. mydat$child_id_age=paste(mydat$experiment,mydat$child_id,mydat$age)
  109. mydat=mydat[order(mydat$experiment,mydat$child_id,mydat$age),] #sort by child ID & age
  110. mydat=mydat[!duplicated(mydat$uchild_id),] #keep only the first line for each child
  111. means=stack(aggregate(mydat[,metrics],by=list(mydat$experiment),mean,na.rm=T)[,-1])
  112. sds=stack(aggregate(mydat[,metrics],by=list(mydat$experiment),sd,na.rm=T)[-1])
  113. df.vars=rbind(df.vars,
  114. cbind(data_set,levels(factor(mydat$experiment)),data.frame(table(mydat$experiment))$Freq,means[,c(2,1)],sds[,-2]))
  115. }
  116. colnames(df.vars)<-df.vars.cols
  117. ```
  118. ```{r generate-data, eval=RECALC}
  119. alldays=NULL
  120. for(i in 1:nrow(df.vars)) for(myr in c(.1,.3,.5, .7, .9)){#i=2;myr=.5
  121. #use a while loop to make sure data generated are close to the target r
  122. C <- matrix(c( 1, myr,myr,1), nrow=2)
  123. simulation_unsatisfactory <- TRUE
  124. while(simulation_unsatisfactory==TRUE){
  125. try.this <- as.data.frame(
  126. genCorData(df.vars$n[i], mu = c(df.vars$mean[i],df.vars$mean[i]), sigma = df.vars$sd[i], corMatrix = C) )
  127. try.this <- try.this[,-1] #remove the ID column, since it's useless
  128. sim.cor <- cor.test(try.this$V1,try.this$V2)$estimate
  129. simulation_unsatisfactory = !(abs(sim.cor-myr)<0.01)
  130. }
  131. thisdat=cbind(df.vars$data_set[i],df.vars$experiment[i],1:df.vars$n[i],stack(try.this),as.character(df.vars$metric[i]),myr)
  132. colnames(thisdat)<-c("data_set","experiment","child_id","value","day","metric","myr")
  133. alldays=rbind(alldays,thisdat)
  134. }#end i
  135. write.csv(alldays,"../output/simulated_correlated_2day.csv",row.names=F)
  136. ```
  137. ## Create ICC dataframe
  138. ```{r, eval=RECALC}
  139. read.csv("../output/simulated_correlated_2day.csv")->alldays
  140. df.icc.mixed.cols = c("data_set", "metric", "iqr", # removed "age_bin",
  141. #"age_b","age_se","age_t", # beta, standard error, T #removed age
  142. "icc_adjusted", "icc_conditional",
  143. "icc_child_id", "icc_corpus",
  144. "child_id_var","corpus_var","residual_var",
  145. "child_id_sd","corpus_sd","residual_sd",
  146. "nobs","nchi", "ncor",
  147. "formula","sw","myr")
  148. df.icc.mixed = data.frame(matrix(ncol=length(df.icc.mixed.cols),nrow=0, dimnames=list(NULL, df.icc.mixed.cols)),
  149. stringsAsFactors = FALSE)
  150. for(myr in levels(factor(alldays$myr)))for(data_set in levels(factor(alldays$data_set))) for(metric in levels(factor(alldays$metric[alldays$data_set==data_set]))) { # myr=.5 ; data_set = "aclew"; metric="wc_adu_ph"
  151. #select data
  152. mydat=alldays[alldays$myr==myr & alldays$data_set==data_set & alldays$metric==metric,]
  153. #reshape mydat so that it fits expectation from the following function
  154. colnames(mydat)[4]<-metric
  155. icc.row <- new_fit_models(mydat, data_set, metric, TRUE) #removed age NA,
  156. df.icc.mixed[nrow(df.icc.mixed) + 1,] <- cbind(icc.row,myr)
  157. }
  158. write.csv(df.icc.mixed,"../output/df.icc.simu.csv",row.names=F)
  159. ```
  160. ## Analyze ICCs
  161. What is the relationship between ICC and r? It looks like they are similar, but ICC undershoots. But just a little - nothing like squaring.
  162. ```{r}
  163. read.csv("../output/df.icc.simu.csv")->df.icc.mixed
  164. plot(df.icc.mixed$icc_child_id~df.icc.mixed$myr)
  165. ```
  166. What is the relationship between iqr & ICC? None
  167. ```{r}
  168. ggplot(df.icc.mixed, aes(iqr,icc_child_id, color=myr)) + geom_point()
  169. ```
  170. What is the relationship between iqr & SW? None
  171. ```{r}
  172. ggplot(df.icc.mixed, aes(icc_child_id, sw, color=myr)) + geom_point()
  173. ```