What does the following code do? source("preproc.R") set.seed(123)…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
What does the following code do?
source("preproc.R") set.seed(123) ################################################################################ #1----------- Get empty models to calculate "unadjusted" ICCs with bootstrap CI
iccs <- data.table("Score" = names(score_pairs), "iccMedian" = NaN, "iccLower" = NaN, "iccUpper" = NaN)
for (name in names(score_pairs)) {
empty_model <- lme4::lmer(get(name) ~ 1 + (1|pseudonym) + (1|praxis), data = longdata_full)
boot_lme <- bootMer(empty_model, FUN = icc_fun_lme, nsim = 5000, type = "parametric")
iccs[Score == name, iccMedian := median(boot_lmet, probs = 0.025)] iccs[Score == name, iccUpper := quantile(boot_lme$t, probs = 0.975)] }
################################################################################ #2----------- Estimate random intercept LMMs for each outcome with bootstrap CI
lme_models <- sapply(names(score_pairs), function(name){
model <- lme4::lmer(get(name) ~ 1 + group + time + group:time + (1|pseudonym) + (1|praxis), data = longdata_full)
}, simplify = FALSE, USE.NAMES = TRUE)
################################################################################ #--------------- Result table with REML-treatment effect estimation and
results <- rbindlist( lapply(lme_models, function(model){
fe <- fixef(model)["group:time"]
ci <- confint(model, method = "boot", parm = "group:time")
boot_lme <- bootMer(model,
FUN = icc_fun_lme,
nsim = 5000,
type = "parametric")
data.table("TreatmentEffect" = fe,
"teLower" = ci[1],
"teUpper" = ci[2],
"iccMedian" = median(boot_lme$t),
"iccLower" = quantile(boot_lme$t, probs = 0.025),
"iccUpper" = quantile(boot_lme$t, probs = 0.975))
} ), idcol = TRUE)
################################################################################ #-------------- get Data for plot. Population prediction without random effects
plotData <- rbindlist( lapply(lme_models, function(model){
# Bootstrap
merBoot <- bootMer(model, predict_lmer, nsim = 1000, re.form = NA)
preds <- data.table(expand.grid(pseudonym = NA,
praxis = NA,
group = 0:1,
time = 0:1)
)
preds[, median := apply(merBoot$t, 2, median)]
preds[, conf.low := apply(merBoot$t, 2, quantile, probs = 0.025)]
preds[, conf.high := apply(merBoot$t, 2, quantile, probs = 0.975)]
preds[, group := factor(group, levels = c(1, 0), labels = c("IG", "CG"))]
return(preds)
}), idcol = TRUE)
prediction_plot <- ggplot(data = plotData,
aes(x = time, y = median, ymin = conf.low, ymax = conf.high,
color = group, fill = group)) +
geom_ribbon(alpha = 1/3, linewidth = 0) +
geom_line(linewidth = 1) +
scale_fill_manual(values = c("IG" = "red", "CG" = "blue")) +
scale_color_manual(values = c("IG" = "red", "CG" = "blue")) +
scale_x_continuous(breaks = 0:1, labels = c("Pre", "Post"),
expand = c(0.1, 0.1)) +
scale_y_continuous("Score", sec.axis = dup_axis(name = NULL)) +
labs(color = "Group", fill = "Group") + # Proper group label
theme_minimal() +
theme(
axis.title.x = element_text(margin = margin(t = 10)),
axis.title.y = element_text(margin = margin(r = 10)),
legend.position = "top", # Move legend for clarity
panel.spacing = unit(2, "lines") # Increase space between facets
) +
ggtitle("Population-mean trajectories",
subtitle = "Bootstrap Predictions with 95% Prediction Interval") +
facet_wrap(~.id, scales = "free_y", ncol = 2, labeller = as_labeller(c(
"PHQ9" = "PHQ9",
"GAD7" = "GAD7",
"PHQ15" = "PHQ15",
"PID5BFM" = "PID5BF+M",
"EBQ" = "EBQ",
"ERQ_CR" = "ERQ_CR",
"ERQ_ES" = "ERQ_ES",
"BEAQ" = "BEAQ"
)))
################################################################################ #-------------------------------- Save Results write.csv2(iccs, file = "Results/Bootstrap_ICCs.csv")
write.csv2(results, file = "Results/Bootstrap_CIs.csv")
ggsave("Results/Prediction_Plot.pdf", plot = prediction_plot, widt = 10, height = 8)
#-------- check ICC plot
ggplot(iccs) + aes(x = Score, y = iccMedian, ymin = iccLower, ymax = iccUpper) + geom_point() + geom_errorbar(aes(colour = "red"))
##########
Also my statistician said that the above script calls the following script. Was does he mean by that:
library(data.table) library(lme4) library(ggplot2) library(marginaleffects) library(readxl)
STARC_merged_data <- read_excel("STARC_merged_data.xlsx")
daten <- as.data.table(copy(STARC_merged_data))
daten[, group := 2 - as.numeric(as.factor(gruppe))]
score_pairs <- list( PHQ9 = c("PHQ9_score_pre", "PHQ9_score_post"), GAD7 = c("GAD7_score_pre", "GAD7_score_post"), PHQ15 = c("PHQ15_score_pre", "PHQ15_score_post"), EBQ = c("EBQ_score_pre", "EBQ_score_post"), ERQ_CR = c("ERQ_CR_score_pre", "ERQ_CR_score_post"), ERQ_ES = c("ERQ_ES_score_pre", "ERQ_ES_score_post"), BEAQ = c("BEAQ_score_pre", "BEAQ_score_post"), PID5BFM = c("PID5BFM_score_pre", "PID5BFM_score_post") )
longdata_full <- copy(daten[, c("group", "praxis", "pseudonym", unlist(score_pairs)), with = FALSE])
longdata_full <- melt(longdata_full, id.vars = c("pseudonym", "praxis", "group"), measure.vars = patterns("^PHQ9", "^GAD7", "^PHQ15", "^EBQ", "^ERQ_CR", "^ERQ_ES", "^BEAQ", "^PID5BFM"), variable.name = "time", value.name = names(score_pairs))
longdata_full[, time := as.numeric(time) - 1] # Convert time to numeric
icc_fun_lme <- function(fit) { vc <- as.data.table(VarCorr(fit)) vp <- vc[grp == "praxis" & var1 == "(Intercept)", vcov] vr <- vc[grp == "Residual", vcov] vs <- vc[grp == "pseudonym" & var1 == "(Intercept)", vcov] vp / (vp + vr + vs) }
predict_lmer <- function(fit){ predict(fit, newdata = expand.grid(pseudonym = NA, praxis = NA, group = 0:1, time = 0:1), re.form = NA) }
Okay, let's break down what this R code does, step by step, including the role of the preproc.R script.
Overall Goal:
The code analyzes longitudinal data (likely pre- and post-intervention scores for various psychological scales) using linear mixed-effects models (LMMs). It aims to:
praxis, representing clinics or similar structures).What source("preproc.R") Does:
When the main script executes source("preproc.R"), it means the R interpreter runs all the code found within the preproc.R file first. This is crucial because preproc.R does the essential setup:
data.table: For efficient data manipulation.lme4: For fitting linear mixed-effects models.ggplot2: For creating plots.marginaleffects: Potentially for effect calculations (though not explicitly used in the shown main script snippet, it's often used with LMMs).readxl: To read data from Excel files."STARC_merged_data.xlsx".data.table named daten.group variable (1 for "IG", 0 for "CG") based on an existing factor variable gruppe.score_pairs"PHQ9_score_pre""PHQ9_score_post"pseudonym, praxis, group, and all score columns) into longdata_full.melt. In the long format, there's a single time variable (indicating pre or post) and a single value variable holding the score. This is the standard format required for many modeling functions, including lme4.time variable (0 for pre, 1 for post).icc_fun_lme: A custom function designed to calculate the ICC from a fitted lme4 model. It extracts variance components for praxis, Residual (within-unit variance), and pseudonym and calculates the ICC as the ratio of praxis variance to the total variance (praxis + Residual + pseudonym).predict_lmer: A function used with bootstrapping to predict population-level outcomes (ignoring random effects) for specified new data points (combinations of group and time).Main Script Analysis:
After preproc.R has run, the main script executes the following sections:
Section 1: Get empty models to calculate "unadjusted" ICCs
data.table called iccs to store the results.score_pairs.lmer) for the current score. The model structure get(name) ~ 1 + (1|pseudonym) + (1|praxis) means it only includes an overall intercept (1) and random intercepts for pseudonym and praxis. This model purely estimates the variance components without accounting for any group or time effects.bootMer to perform bootstrap resampling on this empty model. For each bootstrap sample (nsim = 5000), it applies the icc_fun_lme function to calculate an ICC.iccs table, associated with the current score name.Section 2: Estimate random intercept LMMs for each outcome
sapply to loop through each outcome score name again.get(name) ~ 1 + group + time + group:time + (1|pseudonym) + (1|praxis). This model includes:
1: Overall intercept.group: Main effect of group (CG vs IG).time: Main effect of time (pre vs post).group:time: The interaction effect, representing the core treatment effect – whether the change from pre to post differs between the IG and CG.(1|pseudonym) + (1|praxis): Random intercepts to account for the hierarchical structure (e.g., multiple measurements within individuals, individuals within clinics).lme_models.Section 3: Result table with REML-treatment effect estimation and Bootstrap CIs plus Model "adjusted" ICC
lme_models created in the previous step.group:time interaction (fe <- fixef(model)["group:time"]), which is the estimated average treatment effect.ci) for this group:time effect using confint.bootMer on the adjusted model (the one with fixed effects) with FUN = icc_fun_lme to get bootstrap estimates of the ICC from this adjusted model.data.table).rbindlist combines these rows for all scores into the results table. idcol = TRUE adds a column identifying the score name.Section 4: get Data for plot. Population prediction without random effects
lme_models again.bootMer with the predict_lmer function. This generates predictions of the population average score (ignoring the random effects) for all combinations of group (CG/IG) and time (pre/post) across 1000 bootstrap simulations (nsim = 1000).plotData) with appropriate labels ("CG", "IG", "Pre", "Post"). idcol = TRUE adds the score name.Plotting (prediction_plot)
ggplot2 to create a plot using the plotData.median predicted score against time, with confidence intervals shown as ribbons (geom_ribbon) and the median prediction as lines (geom_line).facet_wrap(~.id, ...).Save Results
write.csv2 saves the calculated iccs and results tables to CSV files in a "Results" directory.ggsave saves the generated prediction_plot as a PDF file.Check ICC Plot
In summary:
The code first sets up the data and necessary functions using preproc.R. Then, it performs a detailed analysis of longitudinal outcome data using mixed-effects models. It calculates baseline (unadjusted) ICCs, fits models that include treatment effects, estimates these treatment effects with confidence intervals, calculates ICCs adjusted for the model, generates population-level predictions for visualization, and finally saves all results and plots. The statistician likely meant that the main script is dependent on the data preparation and function definitions provided by preproc.R to execute correctly.