# Source-ready analysis. Set working directory to the folder containing the raw CSV and roster. # Cohort is fixed by saved parent-paper IDs, never by a new random draw. raw_file <- 'lai_art_acceptance_v1(1).csv' roster_file <- 'Readiness_Parent_Main_232_Roster.csv' q13_yes_code <- 1L # Verified against LAI_ART_Data_Dictionary(1).xlsx, 1=Yes, 0=No. out <- 'financial_attendance_outputs_v4' dir.create(tempdir(), recursive=TRUE, showWarnings=FALSE) if (!file.exists(raw_file) && file.exists('lai_art_acceptance_v1.csv')) raw_file <- 'lai_art_acceptance_v1.csv' if (!file.exists(raw_file) || !file.exists(roster_file)) stop('Place the raw CSV and parent 232-person roster in the working directory.') required <- c('sandwich','ggplot2','MASS') missing_pkgs <- required[!vapply(required,requireNamespace,logical(1),quietly=TRUE)] if(length(missing_pkgs)) stop('Install these packages first: ',paste(missing_pkgs,collapse=', ')) dir.create(out,recursive=TRUE,showWarnings=FALSE) save_csv <- function(x,name) write.csv(x,file.path(out,paste0(name,'.csv')),row.names=FALSE,na='') raw <- read.csv(raw_file,check.names=FALSE,stringsAsFactors=FALSE) roster <- read.csv(roster_file,check.names=FALSE,stringsAsFactors=FALSE) stopifnot(nrow(roster)==232,!anyDuplicated(roster$instanceID),!anyDuplicated(raw$instanceID)) ix <- match(roster$instanceID,raw$instanceID) if(anyNA(ix)) stop('Some parent IDs are absent from the raw data. Do not substitute records.') d <- raw[ix,,drop=FALSE] d$group <- factor(ifelse(roster$parent_group=='PLHIV','PLHIV','PrEP client')) stopifnot(all(table(d$group)==116)) needed <- c('Q02','Q03','Q04','Q11','Q12','Q13','Q14','Q43') stopifnot(all(needed %in% names(d))) for(v in needed) d[[v]] <- suppressWarnings(as.numeric(d[[v]])) for(v in c('Q12','Q14')) if(any(!is.na(d[[v]]) & !d[[v]] %in% 1:5)) stop('Unexpected codes: ',v) if(any(!is.na(d$Q43) & !d$Q43 %in% 1:4)) stop('Unexpected Q43 codes') d$age_group <- factor(ifelse(d$Q02<25,'15-24','25+'),levels=c('25+','15-24')) d$sex <- factor(d$Q04,levels=1:2,labels=c('Male','Female')) d$attendance_concern <- ifelse(is.na(d$Q43),NA_integer_,as.integer(d$Q43>=3)) d$financial_distress <- ifelse(is.na(d$Q12),NA_integer_,as.integer(d$Q12>=3)) d$food_shortage <- ifelse(is.na(d$Q13),NA_integer_,as.integer(d$Q13==1)) if(any(!is.na(d$Q13) & !d$Q13 %in% c(0,1))) stop('Unexpected Q13 codes') d$transport <- relevel(factor(d$Q11,levels=1:5,labels=c('Walking','Public transport','Private vehicle','Boda boda','Other')),ref='Public transport') d$food_worry <- ifelse(is.na(d$Q14),NA_integer_,as.integer(d$Q14>=3)) # Binary labels refer to sometimes/often/always versus never/rarely. # Food worry and financial distress are tested separately to avoid assuming independent constructs. save_csv(data.frame(variable=needed,missing=sapply(d[needed],function(x)sum(is.na(x)))),'01_missingness') save_csv(as.data.frame(table(d$group,d$Q43,useNA='ifany')),'02_full_attendance_response') save_csv(as.data.frame(table(d$Q13,useNA='ifany')),'03_Q13_verified_response_frequencies') summ <- function(dat,var){ do.call(rbind,lapply(split(dat,dat[[var]],drop=TRUE),function(z){n<-sum(!is.na(z$attendance_concern)); k<-sum(z$attendance_concern==1,na.rm=TRUE);ci<-if(n)prop.test(k,n,correct=FALSE)$conf.int else c(NA,NA);data.frame(category=as.character(z[[var]][1]),n=n,concerned=k,percent=100*k/n,lower=100*ci[1],upper=100*ci[2])})) } for(v in c('group','age_group','sex','financial_distress','food_worry','food_shortage','transport')) save_csv(summ(d,v),paste0('04_concern_by_',v)) model <- function(formula,dat,label){ vars<-all.vars(formula);z<-dat[complete.cases(dat[,vars,drop=FALSE]),,drop=FALSE] if(length(unique(z$attendance_concern))<2) return(NULL) fit<-glm(formula,family=poisson(link='log'),data=z) if(!fit$converged) stop('Model did not converge: ',label) V<-sandwich::vcovHC(fit,type='HC0');b<-coef(fit);se<-sqrt(diag(V)) res<-data.frame(model=label,term=names(b),PR=exp(b),lower=exp(b-1.96*se),upper=exp(b+1.96*se),p=2*pnorm(-abs(b/se)),n=nrow(z),events=sum(z$attendance_concern),max_fitted=max(fitted(fit))) save_csv(res,paste0('model_',label));res } results<-list() for(v in c('financial_distress','food_worry','food_shortage')){ results[[paste0(v,'_crude')]]<-model(reformulate(v,'attendance_concern'),d,paste0(v,'_crude')) results[[paste0(v,'_adjusted')]]<-model(reformulate(c(v,'group','age_group','sex'),'attendance_concern'),d,paste0(v,'_adjusted')) results[[paste0(v,'_Q03_yes')]]<-model(reformulate(c(v,'group','age_group','sex'),'attendance_concern'),d[which(d$Q03==1),],paste0(v,'_Q03_yes')) } # Sensitivity: highly concerned only. z<-d;z$attendance_concern<-ifelse(is.na(z$Q43),NA_integer_,as.integer(z$Q43==4)) for(v in c('financial_distress','food_worry','food_shortage')) results[[paste0(v,'_high_concern')]]<-model(reformulate(c(v,'group','age_group','sex'),'attendance_concern'),z,paste0(v,'_high_concern')) all_results<-do.call(rbind,results);save_csv(all_results,'05_all_prevalence_ratios') # Transport remains exploratory, public transport is the reference. transport_fit <- model(attendance_concern~transport+group+age_group+sex,d,'transport_adjusted') save_csv(summ(d,'transport'),'07_transport_descriptive') # Primary exposure choice made after reviewing v1 outputs, not prespecified before analysis. # Avoid adjusting for a risk score containing Q43, which would include the outcome. # Multiple-response conditions: denominator is each hardship stratum with recorded parent response. # A missing parent response is never converted into unselected options. condition_tables<-list() for(spec in list(c('Q31','Q31/3','Transport support'),c('Q31','Q31/2','Flexible appointments'),c('Q32','Q32/6','Cost or transport reason'))){ parent<-spec[1];item<-spec[2];label<-spec[3] if(!all(c(parent,item) %in% names(d))) stop('Missing multiple-response field: ',item) z<-d if(parent=='Q32') z<-z[which(z$Q29 %in% 1:3),] answered<-!is.na(z[[parent]]) & trimws(as.character(z[[parent]]))!='' z<-z[answered & !is.na(z$financial_distress),] # Parent select_multiple strings provide a consistent selection source. selected<-vapply(strsplit(trimws(as.character(z[[parent]])),'[ ,;]+'),function(x)sub('.*/','',item) %in% x,logical(1)) z$selected<-as.integer(selected) for(g in c('All',levels(d$group))){ zz<-if(g=='All')z else z[z$group==g,] tab<-table(factor(zz$financial_distress,levels=0:1),factor(zz$selected,levels=0:1)) pv<-if(sum(tab)>0 && all(rowSums(tab)>0))fisher.test(tab)$p.value else NA_real_ for(h in 0:1){w<-zz[zz$financial_distress==h,];n<-nrow(w);k<-sum(w$selected) condition_tables[[length(condition_tables)+1]]<-data.frame(item=label,group=g,financial_distress=h,n=n,selected=k,percent=if(n)100*k/n else NA_real_,fisher_p=pv) } } } conditions<-do.call(rbind,condition_tables);save_csv(conditions,'10_hardship_service_support') # Secondary exploratory transport-support interaction, added after v1 review. support_d<-d[!is.na(d$Q31) & trimws(as.character(d$Q31))!='',] support_d$attendance_concern<-as.integer(vapply(strsplit(trimws(as.character(support_d$Q31)),'[ ,;]+'),function(x)'3' %in% x,logical(1))) support_d<-support_d[complete.cases(support_d[,c('attendance_concern','financial_distress','group','age_group','sex')]),] # Pooled common-effect summary; retain the interaction analysis to describe uncertainty. support_pooled<-model(attendance_concern~financial_distress+group+age_group+sex,support_d,'transport_support_pooled_exploratory') save_csv(subset(support_pooled,term=='financial_distress'),'13b_transport_support_pooled_exploratory') support_formula<-attendance_concern~financial_distress*group+age_group+sex support_summary<-model(support_formula,support_d,'transport_support_interaction_exploratory') support_fit<-glm(support_formula,family=poisson(link='log'),data=support_d) bs<-coef(support_fit);Vs<-sandwich::vcovHC(support_fit,type='HC0') interaction_term<-grep('financial_distress:group',names(bs),value=TRUE) if(length(interaction_term)!=1L) stop('Could not identify support interaction term') contrast_support<-function(label,terms){ L<-setNames(rep(0,length(bs)),names(bs));L[terms]<-1 b<-sum(L*bs);se<-sqrt(as.numeric(t(L)%*%Vs%*%L)) data.frame(contrast=label,PR=exp(b),lower=exp(b-1.96*se),upper=exp(b+1.96*se),p=2*pnorm(-abs(b/se)),n=nrow(support_d),events=sum(support_d$attendance_concern),max_fitted=max(fitted(support_fit))) } support_contrasts<-rbind(contrast_support('Distress within PLHIV','financial_distress'),contrast_support('Distress within PrEP clients',c('financial_distress',interaction_term)),contrast_support('Distress by service-group interaction',interaction_term)) save_csv(support_contrasts,'13_transport_support_interaction_contrasts_exploratory') # A significant contrast in one group and a non-significant contrast in another is not an interaction test. # Wilson confidence intervals for all reported condition proportions. wilson<-function(k,n){ if(n==0)return(c(NA_real_,NA_real_)) z<-qnorm(.975);pp<-k/n;den<-1+z^2/n;cen<-(pp+z^2/(2*n))/den;half<-z*sqrt(pp*(1-pp)/n+z^2/(4*n^2))/den bounds<-pmax(0,pmin(100,100*c(cen-half,cen+half))) if(k==0)bounds[1]<-0 if(k==n)bounds[2]<-100 bounds } ci<-t(mapply(wilson,conditions$selected,conditions$n)) conditions$lower<-ci[,1];conditions$upper<-ci[,2] save_csv(conditions,'10_hardship_service_support_with_CI') # Figure 1 is specific to this paper: hardship within service groups. library(ggplot2) f1<-do.call(rbind,lapply(split(d,d$group),function(z){a<-summ(z,'financial_distress');a$group<-as.character(z$group[1]);a})) f1$hardship<-factor(f1$category,levels=c('0','1'),labels=c('Never/rarely','Sometimes or more often')) p<-ggplot(f1,aes(hardship,percent,color=group))+geom_point(size=3)+geom_errorbar(aes(ymin=lower,ymax=upper),width=.12)+geom_text(aes(label=paste0(concerned,'/',n)),nudge_x=.16,hjust=0,size=3.5)+facet_wrap(~group)+scale_color_manual(values=c('#167D9A','#B45135'))+scale_y_continuous(limits=c(0,100))+labs(x='Financial distress',y='Clinic attendance concern (%)')+theme_classic(base_size=11)+theme(legend.position='none',axis.text.x=element_text(size=9)) ggsave(file.path(out,'Figure_1_Concern_By_Financial_Distress.png'),p,width=9,height=4.5,dpi=300) # Figure 2: the complete response distribution for the primary exposure. f2<-as.data.frame(table(d$group,d$financial_distress,factor(d$Q43,levels=1:4,labels=c('Not concerned','Neutral','Concerned','Highly concerned')))) names(f2)<-c('group','hardship','response','n') f2n<-aggregate(n~group+hardship,f2,sum) f2$hardship<-factor(f2$hardship,levels=c('0','1'),labels=c('Never/rarely','Sometimes or more often')) f2n$hardship<-factor(f2n$hardship,levels=c('0','1'),labels=c('Never/rarely','Sometimes or more often')) p<-ggplot(f2,aes(hardship,n,fill=response))+geom_col(position='fill',width=.65)+geom_text(data=f2n,aes(x=hardship,y=-.06,label=paste0('n=',n)),inherit.aes=FALSE,size=3.5)+facet_wrap(~group)+scale_y_continuous(labels=function(x)paste0(round(x*100),'%'))+scale_fill_manual(values=c('#CDDDE5','#A7B3BC','#E2A15B','#A64C32'))+coord_cartesian(ylim=c(-.1,1),clip='off')+labs(x='Financial distress',y='Q43 response distribution',fill=NULL)+theme_classic(base_size=11)+theme(legend.position='bottom',axis.text.x=element_text(size=9))+guides(fill=guide_legend(nrow=2)) ggsave(file.path(out,'Figure_2_Full_Concern_Distribution.png'),p,width=9,height=5,dpi=300) # Figure 3 shows prevalence ratios only. Ordinal ORs remain in a separate table. ff<-subset(all_results,term %in% c('financial_distress','food_worry','food_shortage') & !grepl('high_concern',model)) ff$method<-ifelse(grepl('Q03_yes',ff$model),'Q03 = Yes',ifelse(grepl('adjusted',ff$model),'Adjusted','Crude')) ff$exposure<-ff$term ff<-ff[,c('exposure','method','PR','lower','upper')] if(exists('std')) { ll<-do.call(rbind,std);ll$PR<-ll$standardised_PR;ll$method<-'Logistic standardised' ff<-rbind(ff,ll[,c('exposure','method','PR','lower','upper')]) } ff$exposure<-factor(ff$exposure,levels=c('financial_distress','food_worry','food_shortage'),labels=c('Financial distress (primary)','Food worry (secondary)','Meal skipping or reduced portions (secondary)')) ff$method<-factor(ff$method,levels=rev(c('Crude','Adjusted','Q03 = Yes','Logistic standardised'))) p<-ggplot(ff,aes(PR,method))+geom_vline(xintercept=1,linetype=2,color='grey50')+geom_segment(aes(x=lower,xend=upper,yend=method))+geom_point(size=2.5,color='#167D9A')+facet_wrap(~exposure,ncol=1)+scale_x_log10()+labs(x='Prevalence ratio (95% CI)',y=NULL)+theme_classic(base_size=11) ggsave(file.path(out,'Figure_3_Model_Comparison.png'),p,width=8,height=8,dpi=300) # Optional Figure 4 is generated regardless of significance for review, not selected by p-value. f4<-subset(conditions,item!='Cost or transport reason' & group!='All') f4$hardship<-factor(f4$financial_distress,levels=0:1,labels=c('Never/rarely','Sometimes or more often')) f4$y<-as.numeric(factor(f4$item,levels=c('Flexible appointments','Transport support')))+ifelse(f4$financial_distress==0,-.12,.12) p<-ggplot(f4,aes(percent,y,color=hardship))+geom_segment(aes(x=lower,xend=upper,yend=y))+geom_point(size=3)+geom_text(aes(x=upper+3,label=paste0(selected,'/',n)),hjust=0,size=3,show.legend=FALSE)+facet_wrap(~group)+scale_x_continuous(limits=c(0,112),breaks=c(0,25,50,75,100))+scale_y_continuous(breaks=1:2,labels=c('Flexible appointments','Transport support'),limits=c(.5,2.5))+scale_color_manual(values=c('#167D9A','#B45135'))+labs(x='Selected condition (%)',y=NULL,color='Financial distress')+theme_classic(base_size=11)+theme(legend.position='bottom') ggsave(file.path(out,'Figure_4_Service_Support_Exploratory.png'),p,width=9,height=4,dpi=300) writeLines(c('Exact 232 parent IDs, 116 PLHIV and 116 PrEP clients. No new random selection.', 'Financial distress was designated primary after reviewing v1 results. This is a revised exploratory analysis, not an advance prespecification.', 'The pooled transport-support model assumes a common distress PR across groups. A non-significant interaction does not establish equal effects.', 'Service-support interaction and transport analyses are secondary and exploratory. Interpret the interaction test itself, not the difference in separate significance labels.', 'Common ordinal odds ratios are diagnostic only. Report threshold-specific estimates when the global proportional-odds check rejects equal slopes.', 'Global proportional-odds tests assess all model slopes, not only the hardship coefficient.', 'Figure 2 gives stratum sample sizes. Figure 4 gives selected/n and Wilson 95% confidence intervals.', 'Food worry and reported meal skipping/reduced portions are secondary exposures. Both are self-reported.', 'Q13 1=Yes, 0=No verified against the current XLSForm-derived dictionary.', 'Q14 heading says past 30 days, question says past three months. Use question wording, confirm administered wording before manuscript finalisation.', 'Q43 measures concern about strict clinic attendance, not observed attendance or predicted missed appointments.', 'Ordinal ORs describe higher concern categories. They are not prevalence ratios and are kept out of the PR forest plot.', 'Inspect the approximate global slope-equality test and threshold-specific ORs before interpreting a common proportional-odds OR. Null high-concern findings do not establish individual movement between categories.', 'Q31 denominators use recorded parent answers. Q32 is restricted to Q29 codes 1-3 and recorded parent answers. Missing parent responses are excluded, not treated as no selection.', 'Transport modes are described separately. Walking remains a small group. Adjusted transport estimates are exploratory.', 'Figure 4 is exploratory and generated without significance selection. Null results remain documented.', 'No causal sequence is inferred between hardship, concern and service preferences in this cross-sectional survey.', 'Age and PLHIV recruitment sessions remain inseparable. No site covariate is fitted because recruitment was at Mildmay per team clarification.', 'Primary archived dataset and current raw file match on all 232 IDs and Q43/Q30/Q12/Q13/Q14/Q29. Correct Q43 PrEP result: 65/116 and mean 2.465517.', 'Readiness manuscript cross-reference requires its final verified model and publication status. Do not describe an unpublished analysis as published.'),file.path(out,'README.txt')) save_csv(data.frame(group=levels(d$group),n=as.numeric(table(d$group)),concerned=sapply(levels(d$group),function(g)sum(d$attendance_concern[d$group==g])),mean_Q43=sapply(levels(d$group),function(g)mean(d$Q43[d$group==g]))),'11_Q43_reconciliation') save_csv(data.frame(source=c('raw','roster'),md5=c(unname(tools::md5sum(raw_file)),unname(tools::md5sum(roster_file)))),'12_source_fingerprints') capture.output(sessionInfo(),file=file.path(out,'sessionInfo.txt')) message('Core models and figures exported: ',normalizePath(out)) # Export basic figures before optional statistical sections. # Bounded logistic standardisation for each hardship exposure, with bootstrap CIs. set.seed(20260929) standardise<-function(dat,v){ fit<-glm(reformulate(c(v,'group','age_group','sex'),'attendance_concern'),family=binomial(),data=dat) if(!fit$converged) return(NA_real_) a<-b<-dat;a[[v]]<-1;b[[v]]<-0 mean(predict(fit,a,type='response'))/mean(predict(fit,b,type='response')) } std<-lapply(c('financial_distress','food_worry','food_shortage'),function(v){ z<-d[complete.cases(d[,c(v,'group','age_group','sex','attendance_concern')]),] est<-standardise(z,v) boots<-replicate(1000,tryCatch(standardise(z[sample.int(nrow(z),replace=TRUE),],v),error=function(e)NA_real_)) valid<-is.finite(boots)&boots>0 if(sum(valid)<800) stop('Too few valid bootstrap replicates for ',v) ci<-quantile(boots[valid],c(.025,.975),na.rm=TRUE) data.frame(exposure=v,standardised_PR=est,lower=ci[1],upper=ci[2],n=nrow(z),valid_bootstrap=sum(valid)) });save_csv(do.call(rbind,std),'06_logistic_standardisation') # Proportional odds: OR >1 means greater odds of a higher concern category. ordinal_results <- list();po_checks <- list();po_tests<-list() for(v in c('financial_distress','food_worry','food_shortage')){ z<-d[complete.cases(d[,c(v,'group','age_group','sex','Q43')]),] z$concern_ordered<-ordered(z$Q43,levels=1:4) fit<-MASS::polr(reformulate(c(v,'group','age_group','sex'),'concern_ordered'),data=z,Hess=TRUE,method='logistic') b<-coef(fit);se<-sqrt(diag(vcov(fit)))[names(b)] ordinal_results[[v]]<-data.frame(exposure=v,term=names(b),ordinal_OR=exp(b),lower=exp(b-1.96*se),upper=exp(b+1.96*se),p=2*pnorm(-abs(b/se)),n=nrow(z)) # Approximate global proportional-odds check: threshold-specific slopes, # joint Wald test with participant-clustered covariance for repeated cumulative outcomes. stacked<-do.call(rbind,lapply(1:3,function(k){a<-z;a$threshold<-k;a$above_threshold<-as.integer(a$Q43>k);a$person<-seq_len(nrow(a));a})) stacked$threshold<-factor(stacked$threshold) nf<-glm(as.formula(paste0('above_threshold ~ threshold * (',v,' + group + age_group + sex)')),family=binomial(),data=stacked) ii<-grep(':',names(coef(nf))) VV<-sandwich::vcovCL(nf,cluster=stacked$person,type='HC0')[ii,ii,drop=FALSE] bb<-coef(nf)[ii] test<-tryCatch(as.numeric(t(bb)%*%solve(VV,bb)),error=function(e)NA_real_) po_tests[[v]]<-data.frame(exposure=v,global_Wald=test,df=length(ii),p=pchisq(test,df=length(ii),lower.tail=FALSE),method='Approximate global cumulative-logit slope equality test, participant-clustered Wald') # Threshold-specific models diagnose whether a common OR is plausible. # These estimates are diagnostic, not a formal proportional-odds test. po_checks[[v]]<-do.call(rbind,lapply(1:3,function(k){ z$above_threshold<-as.integer(z$Q43>k) f<-glm(reformulate(c(v,'group','age_group','sex'),'above_threshold'),family=binomial(),data=z) b<-coef(f)[v];se<-sqrt(diag(vcov(f)))[v] data.frame(exposure=v,threshold=paste0('Q43 > ',k),OR=exp(b),lower=exp(b-1.96*se),upper=exp(b+1.96*se)) })) } save_csv(do.call(rbind,ordinal_results),'08_common_ordinal_OR_diagnostics_not_for_reporting') save_csv(do.call(rbind,po_checks),'09_ordinal_threshold_diagnostics') save_csv(do.call(rbind,po_tests),'09b_proportional_odds_check') # Refresh forest plot with standardised estimates after successful completion. # Figure 3 shows prevalence ratios only. Ordinal ORs remain in a separate table. ff<-subset(all_results,term %in% c('financial_distress','food_worry','food_shortage') & !grepl('high_concern',model)) ff$method<-ifelse(grepl('Q03_yes',ff$model),'Q03 = Yes',ifelse(grepl('adjusted',ff$model),'Adjusted','Crude')) ff$exposure<-ff$term ff<-ff[,c('exposure','method','PR','lower','upper')] if(exists('std')) { ll<-do.call(rbind,std);ll$PR<-ll$standardised_PR;ll$method<-'Logistic standardised' ff<-rbind(ff,ll[,c('exposure','method','PR','lower','upper')]) } ff$exposure<-factor(ff$exposure,levels=c('financial_distress','food_worry','food_shortage'),labels=c('Financial distress (primary)','Food worry (secondary)','Meal skipping or reduced portions (secondary)')) ff$method<-factor(ff$method,levels=rev(c('Crude','Adjusted','Q03 = Yes','Logistic standardised'))) p<-ggplot(ff,aes(PR,method))+geom_vline(xintercept=1,linetype=2,color='grey50')+geom_segment(aes(x=lower,xend=upper,yend=method))+geom_point(size=2.5,color='#167D9A')+facet_wrap(~exposure,ncol=1)+scale_x_log10()+labs(x='Prevalence ratio (95% CI)',y=NULL)+theme_classic(base_size=11) ggsave(file.path(out,'Figure_3_Model_Comparison.png'),p,width=8,height=8,dpi=300) # Bounded logistic standardisation for transport, public transport as reference. transport_z<-d[complete.cases(d[,c('transport','group','age_group','sex','attendance_concern')]),] transport_log_fit<-glm(attendance_concern~transport+group+age_group+sex,family=binomial(),data=transport_z) set.seed(20261001) transport_std<-function(z,mode){ f<-glm(attendance_concern~transport+group+age_group+sex,family=binomial(),data=z) if(!f$converged)return(NA_real_) a<-b<-z;a$transport<-factor(rep(mode,nrow(z)),levels=levels(z$transport));b$transport<-factor(rep('Public transport',nrow(z)),levels=levels(z$transport)) mean(predict(f,a,type='response'))/mean(predict(f,b,type='response')) } transport_check<-do.call(rbind,lapply(setdiff(levels(droplevels(transport_z$transport)),'Public transport'),function(mode){ point<-transport_std(transport_z,mode) bb<-replicate(1000,tryCatch(transport_std(transport_z[sample.int(nrow(transport_z),replace=TRUE),],mode),error=function(e)NA_real_)) good<-is.finite(bb)&bb>0 if(sum(good)<800)stop('Too few valid transport bootstrap replicates for ',mode) ci<-quantile(bb[good],c(.025,.975)) data.frame(transport=mode,standardised_PR=point,lower=ci[1],upper=ci[2],n=nrow(transport_z),valid_bootstrap=sum(good),max_logistic_fitted=max(fitted(transport_log_fit))) })) save_csv(transport_check,'14_transport_logistic_standardisation') capture.output(sessionInfo(),file=file.path(out,'sessionInfo.txt')) message('All analyses completed: ',normalizePath(out))