simulate-r-for-icc.R 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. library(simstudy)
  2. check_small_var<-function(x,y,i) round(x[i],3)==round(y[i],3) & round(y[i],3) == 0
  3. fit_child_model<-function(dataframe, metric){
  4. # Fit formula where experiment is removed
  5. formula <- as.formula(paste0(metric, "~ (1|child_id)")) #removed age_s +
  6. model <- lmer(formula, data=dataframe)
  7. return (model)
  8. }
  9. extract_chi_variables<-function(model){
  10. icc.result.mixed <- c(icc(model)$ICC_adjusted,icc(model)$ICC_conditional)
  11. icc.result.split <- c(as.data.frame(icc(model, by_group=TRUE))$ICC, NA)
  12. ranefs_vars <- t(as.data.frame(VarCorr(model))["vcov"])
  13. ranefs_stdv <- t(as.data.frame(VarCorr(model))["sdcor"])
  14. # chi, NA, residual
  15. ranefs_vars <-c(ranefs_vars[1],NA,ranefs_vars[2])
  16. ranefs_stdv <-c(ranefs_stdv[1],NA,ranefs_stdv[2])
  17. # chi, NA
  18. ns<-c(unlist(summary(model)$n),NA)
  19. return (c(#coefficients(summary(model))["age_s",],
  20. icc.result.mixed,
  21. icc.result.split,
  22. ranefs_vars,
  23. ranefs_stdv,
  24. nobs(model),ns))
  25. }
  26. extract_full_variables<-function(model){
  27. icc.result.mixed <- c(icc(model)$ICC_adjusted,icc(model)$ICC_conditional)
  28. icc.result.split <- t(as.data.frame(icc(model, by_group=TRUE))$ICC)
  29. ranefs_vars <- t(as.data.frame(VarCorr(model))["vcov"])
  30. ranefs_stdv <- t(as.data.frame(VarCorr(model))["sdcor"])
  31. ns<-t(data.frame(summary(model)$n))
  32. return (c( # coefficients(summary(model))["age_s",],
  33. icc.result.mixed,
  34. icc.result.split,
  35. ranefs_vars,
  36. ranefs_stdv,
  37. nobs(model),ns))
  38. }
  39. new_fit_models_sim<-function(dataframe, data_set, metric, fit_full = TRUE){ #age,
  40. iqr = quantile(dataframe[,metric],.75,na.rm=T)-quantile(dataframe[,metric],.25,na.rm=T)
  41. if(fit_full){
  42. # Fit full model
  43. formula <- as.formula(paste0(metric, "~ (1|experiment/child_id)")) #removed age_s +
  44. model <- lmer(formula, data=dataframe)
  45. }
  46. if(fit_full & !isSingular(model)) # Fitted full model
  47. {
  48. form="full"
  49. sw=shapiro.test(resid(model))$p
  50. mod_variables <- extract_full_variables(model)
  51. # Build line
  52. } else {
  53. model <- fit_child_model(dataframe, metric)
  54. if(!isSingular(model)){
  55. form = "no_exp"
  56. sw=shapiro.test(resid(model))$p
  57. mod_variables <- extract_chi_variables(model)
  58. } else {
  59. form='no_chi_effect'
  60. sw = NA
  61. mod_variables = c(
  62. # NA,NA,NA, # c(coefficients(summary(model))["age_s",]
  63. NA,NA, # icc.result.mixed
  64. NA,NA, # icc.result.split
  65. NA,NA,NA, # ranefs_vars
  66. NA,NA,NA, # raners_std
  67. NA,NA,NA) # nobs (child, corpus), nobs
  68. }
  69. }
  70. icc.row = c(data_set, metric, iqr, mod_variables, form, sw) #age,
  71. return (icc.row)
  72. }
  73. #create matrix to hold info in
  74. df.vars.cols = c("data_set","experiment","n","metric", "mean","sd")
  75. df.vars = data.frame(matrix(ncol=length(df.vars.cols),nrow=0, dimnames=list(NULL, df.vars.cols)), stringsAsFactors=FALSE)
  76. for (data_set in data_sets){ # data_set = "aclew"
  77. mydat <- read.csv(paste0('../data_output/', data_set,'_metrics_scaled.csv')) # TO DISCUSS: scaled or unscaled?
  78. metrics = colnames(mydat)[!is.element(colnames(mydat), no.scale.columns)]
  79. #select down to first recording by child
  80. mydat$uchild_id=paste(mydat$experiment,mydat$child_id)
  81. mydat$child_id_age=paste(mydat$experiment,mydat$child_id,mydat$age)
  82. mydat=mydat[order(mydat$experiment,mydat$child_id,mydat$age),] #sort by child ID & age
  83. mydat=mydat[!duplicated(mydat$uchild_id),] #keep only the first line for each child
  84. means=stack(aggregate(mydat[,metrics],by=list(mydat$experiment),mean,na.rm=T)[,-1])
  85. sds=stack(aggregate(mydat[,metrics],by=list(mydat$experiment),sd,na.rm=T)[-1])
  86. df.vars=rbind(df.vars,
  87. cbind(data_set,levels(factor(mydat$experiment)),data.frame(table(mydat$experiment))$Freq,means[,c(2,1)],sds[,-2]))
  88. }
  89. colnames(df.vars)<-df.vars.cols
  90. alldays=NULL
  91. for(i in 1:nrow(df.vars)) for(myr in c(.1,.3,.5, .7, .9)){#i=2;myr=.5
  92. #use a while loop to make sure data generated are close to the target r
  93. C <- matrix(c( 1, myr,myr,1), nrow=2)
  94. simulation_unsatisfactory <- TRUE
  95. while(simulation_unsatisfactory==TRUE){
  96. try.this <- as.data.frame(
  97. genCorData(df.vars$n[i], mu = c(df.vars$mean[i],df.vars$mean[i]), sigma = df.vars$sd[i], corMatrix = C) )
  98. try.this <- try.this[,-1] #remove the ID column, since it's useless
  99. sim.cor <- cor.test(try.this$V1,try.this$V2)$estimate
  100. simulation_unsatisfactory = !(abs(sim.cor-myr)<0.01)
  101. }
  102. 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)
  103. colnames(thisdat)<-c("data_set","experiment","child_id","value","day","metric","myr")
  104. alldays=rbind(alldays,thisdat)
  105. }#end i
  106. write.csv(alldays,"../output/simulated_correlated_2day.csv",row.names=F)
  107. read.csv("../output/simulated_correlated_2day.csv")->alldays
  108. df.icc.mixed.cols = c("data_set", "metric", "iqr", # removed "age_bin",
  109. #"age_b","age_se","age_t", # beta, standard error, T #removed age
  110. "icc_adjusted", "icc_conditional",
  111. "icc_child_id", "icc_corpus",
  112. "child_id_var","corpus_var","residual_var",
  113. "child_id_sd","corpus_sd","residual_sd",
  114. "nobs","nchi", "ncor",
  115. "formula","sw","myr")
  116. df.icc.mixed = data.frame(matrix(ncol=length(df.icc.mixed.cols),nrow=0, dimnames=list(NULL, df.icc.mixed.cols)),
  117. stringsAsFactors = FALSE)
  118. 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"
  119. #select data
  120. mydat=alldays[alldays$myr==myr & alldays$data_set==data_set & alldays$metric==metric,]
  121. #reshape mydat so that it fits expectation from the following function
  122. colnames(mydat)[4]<-metric
  123. icc.row <- new_fit_models_sim(mydat, data_set, metric, TRUE) #removed age NA,
  124. df.icc.mixed[nrow(df.icc.mixed) + 1,] <- cbind(icc.row,myr)
  125. }
  126. write.csv(df.icc.mixed,"../output/df.icc.simu.csv",row.names=F)