ID
int64 1
1.07k
| Comment
stringlengths 8
1.13k
| Code
stringlengths 10
4.28k
| Label
stringclasses 4
values | Source
stringlengths 21
21
| File
stringlengths 4
82
|
---|---|---|---|---|---|
801 | create one index of political engagement using: interest, media reception, and political action | polit_eng = c("polintr_r_s", "nwspol_s", "polit_action_s") data8$polit_eng = rowMeans(data8[polit_eng], na.rm = TRUE) mean(data8$polit_eng, na.rm = TRUE) # 0.22 sd(data8$polit_eng, na.rm = TRUE) # 0.14 psych::alpha(data8[polit_eng]) # 0.39 data8$polit_eng_c = c(scale(data8$polit_eng, center = TRUE, scale = FALSE)) # center | Data Variable | https://osf.io/k853j/ | ESS_openness_2016.R |
802 | Calculate values scores for PVQ recoding PVQ items (ESS uses 1 as "like me" and 6 "totally not like me) | data8$ipcrtiv_r = 7 - data8$ipcrtiv data8$imprich_r = 7 - data8$imprich data8$ipeqopt_r = 7 - data8$ipeqopt data8$ipshabt_r = 7 - data8$ipshabt data8$impsafe_r = 7 - data8$impsafe data8$impdiff_r = 7 - data8$impdiff data8$ipfrule_r = 7 - data8$ipfrule data8$ipudrst_r = 7 - data8$ipudrst data8$ipmodst_r = 7 - data8$ipmodst data8$ipgdtim_r = 7 - data8$ipgdtim data8$impfree_r = 7 - data8$impfree data8$iphlppl_r = 7 - data8$iphlppl data8$ipsuces_r = 7 - data8$ipsuces data8$ipstrgv_r = 7 - data8$ipstrgv data8$ipadvnt_r = 7 - data8$ipadvnt data8$ipbhprp_r = 7 - data8$ipbhprp data8$iprspot_r = 7 - data8$iprspot data8$iplylfr_r = 7 - data8$iplylfr data8$impenv_r = 7 - data8$impenv data8$imptrad_r = 7 - data8$imptrad data8$impfun_r = 7 - data8$impfun | Data Variable | https://osf.io/k853j/ | ESS_openness_2016.R |
803 | evaluate goodness of fit of psychometric function using deviance test | d_fit <-{} for(i in unique(d$Subject)){ m_1 <- glm(Response ~ JumpSize * Velocity +BlinkDuration , d[d$Subject==i & d$cond1==1,], family=binomial(probit)) m_0<- glm(Response ~ Velocity +BlinkDuration , d[d$Subject==i & d$cond1==1,], family=binomial(probit)) LRT <- anova(m_0, m_1,test="LRT") d_fit <- rbind(d_fit, data.frame(id=i, D=LRT$Deviance[2], df=LRT$Df[2], p=LRT$`Pr(>Chi)`[2])) } print(d_fit,digits=2,row.names=F) round(d_fit$p,digits=10) | Statistical Test | https://osf.io/f6qsk/ | analysis_exp2.R |
804 | use lmList to fit individual GLM models in one go | mo <- lmList(Response ~ cond1 * JumpSize * Velocity +bdur:cond1 | Subject, d, family=binomial(probit)) | Statistical Modeling | https://osf.io/f6qsk/ | analysis_exp2.R |
805 | visualize Bayes factors and parameter estimates | par(mfrow=c(1,2)) slope_bdur <- B[,8] / (((B[,3]+B[,5]) + (B[,3]+B[,7]+B[,5]+B[,9]))/2) slope_bayes <- outB$beta_5 / (((outB$beta_2) + (outB$beta_2+outB$beta_4))/2) | Visualization | https://osf.io/f6qsk/ | analysis_exp2.R |
806 | sanity check to ensure that we get same estimates from frequentist or Bayesian analysis | plot(slope_bdur, slope_bayes, ylab="slope (Bayesian)",xlab="slope (frequentist)", pch=19) abline(a=0,b=1,lty=2) cor.test(slope_bdur, slope_bayes) | Statistical Test | https://osf.io/f6qsk/ | analysis_exp2.R |
807 | n: sample size of each study simtot: number of simulations seed 1 Compute d33, ncp33 and df for the original sample | d33=pwr.t.test(n=n,sig.level=0.05,power=1/3,type="two.sample")$d ncp33=sqrt(n/2)*d33 df=2*n-2 | Data Variable | https://osf.io/ujpyn/ | [2]R-AnswerstoRound3Reviews-Powertoacceptflatwhentrueeffectiszeroacross24studies.R |
808 | point estimate p hat (just mean average of coefficients) | pe <-mean(cors) | Data Variable | https://osf.io/9jzfr/ | metaBigFive.R |
809 | next, we use the bridge_sampler() function which will stabilize the calculated BFs see Schad et al 2022 https://psycnet.apa.org/doi/10.1037/met0000472 | model.intox.seq.bf <- bridge_sampler(model.intox.seq, silent = TRUE) model.intox.seq.null.bf <- bridge_sampler(model.intox.seq.null, silent = TRUE) | Statistical Modeling | https://osf.io/rh2sw/ | bayes.ema.tutorial.analysis.R |
810 | figure out which columns contain NAs | missing_cols <- colSums(is.na(data.conseq)) > 0 print(names(data.conseq)[missing_cols]) | Data Variable | https://osf.io/rh2sw/ | bayes.ema.tutorial.analysis.R |
811 | age recored as 1 18, to correct we added 17 to all age variables | data$age <- data$age + 17 | Data Variable | https://osf.io/zfqax/ | Study1_manipulationeffectiveness.R |
812 | User language variable into a factor | data$UserLanguage <- ifelse(data$UserLanguage == "EN", "EN", "NL") data$UserLanguage <- as.factor(data$UserLanguage) contrasts(data$UserLanguage) <- c(0, 1) | Data Variable | https://osf.io/zfqax/ | Study1_manipulationeffectiveness.R |
813 | Test assumptions MANOVA Test whether residuals are normally distributed | df$pc1.residuals = lm(pc1~condition.breach, data=df)$residuals df$pc2.residuals = lm(pc2~condition.breach, data=df)$residuals df$pc3.residuals = lm(pc3~condition.breach, data=df)$residuals df$pc4.residuals = lm(pc4~condition.breach, data=df)$residuals shapiro.test(df$pc1.residuals) shapiro.test(df$pc2.residuals) shapiro.test(df$pc3.residuals) shapiro.test(df$pc4.residuals) | Statistical Test | https://osf.io/qj86m/ | 7_manova_fda_breach.R |
814 | Plot effect of first and third principal component | eigenfunctions.df = read.table(file="../data/final/eigenfunctions_breach.dat", header=T) fig.df1 <- data.frame(HR = c(eigenfunctions.df$pc1*-0.0305, eigenfunctions.df$pc1*0.1355), Condition = rep(c(rep("Breach", 51), rep("Fulfilment", 51))), Time=rep(seq(0,1, by=1/50),2), pc="Principal component 1") fig.df2 <- data.frame(HR = c(eigenfunctions.df$pc3*0.0278, eigenfunctions.df$pc3*-0.0617), Condition = rep(c(rep("Breach", 51), rep("Fulfilment", 51))), Time=rep(seq(0,1, by=1/50),2), pc="Principal component 3") fig.df = rbind(fig.df1, fig.df2) fig <- ggplot(fig.df, aes(x=Time, y =HR, linetype=Condition))+ geom_line()+ geom_vline(xintercept=.20, linetype="dashed")+ facet_grid(~pc)+ theme_bw() fig ggsave(file="../figures/figure3.png", width=8, height=6) | Visualization | https://osf.io/qj86m/ | 7_manova_fda_breach.R |
815 | function pcor2beta gives you data from a partial correlation/network input pcor a partial correlation matrix / network output a matrix of betas, each column corresponds to a dependent variable so that you can get predicted values by a matrix multiplication in the form betas %*% data | pcor2beta <- function(pcor) { require(psych) require(corpcor) diag(pcor) <- 1 p <- ncol(pcor) betas <- matrix(0, ncol = p, nrow = p) for(i in 1:p) betas[-i,i] <- matReg(y = i, x = seq(p)[-i], C = pcor2cor(pcor))$beta betas[abs(betas) < 1e-13] <- 0 betas } | Statistical Modeling | https://osf.io/ywm3r/ | predictability.R |
816 | function R2 gives you two different types of R2 and of predicted values input pcor a partial correlation matrix / network output a matrix of betas, each column corresponds to a dependent variable so that you can get predicted values by a matrix multiplication in the form betas %*% data this function gives you R2 and predicted values from betas + data two types of R2 and predicted values are considered: R2_orig and predicted_orig use beta weights directly implied by the graphical lasso regularization R2_refit and predicted_refit use only the sparsity pattern of the network and then refit linear regression using the network only for prediction but not for shrinkage (this one should do better in terms of prediction) refit: logical, regulates whether R2_refit and predicted_refit are computed. set it to FALSE to speed up computations | R2 <- function(betas, dt, refit = TRUE) { dt <- data.frame(scale(dt)) out <- list() p <- ncol(betas) | Statistical Modeling | https://osf.io/ywm3r/ | predictability.R |
817 | refit the model considering the sparsity pattern inicated by the network first fit regression using the sparsity indciated in the matrix of betas | betas_refit <- matrix(0, ncol = p, nrow = p) for(i in 1:p) { if(any(betas[,i] != 0)) { fit <- lm(dt[,i] ~ as.matrix(dt[,betas[,i] != 0])) betas_refit[betas[,i] != 0, i] <- fit$coefficients[-1] } else betas_refit[,i] <- 0 } predicted <- as.matrix(dt) %*% betas_refit | Statistical Modeling | https://osf.io/ywm3r/ | predictability.R |
818 | fit the data using the lm function | bcafit <- lm(Abs562 ~ BSA, data = bca) | Statistical Modeling | https://osf.io/9e3cu/ | BCA_dilution_answers.R |
819 | rename the columns for display | colnames(samptab) <- c("Absorbance", "Concentration (mg/mL)") | Data Variable | https://osf.io/9e3cu/ | BCA_dilution_answers.R |
820 | departure time (12 hours so we can calculate easy the mean) | d1[, time_ := strftime(datetime_ - 60*60*12, format="%H:%M:%S")] d1[, time_ := as.POSIXct(time_, format="%H:%M:%S")] | Data Variable | https://osf.io/amd3r/ | R_script_tables_and_figures.R |
821 | This creates a variable "period" in the dataframe myDataISO: | myDataISO$period<-gl(2, 1202, labels = c("first", "second")) # We created 2 sets of 1202 scores, the labels option then specifies the names to attach to these 2 sets, which correspond to the levels of "period" (first measurement and follow-up). | Data Variable | https://osf.io/wcqpa/ | Rcode.R |
822 | MIXED DESIGNS AS A GLM Setting contrasts for quarantine subperiod: | myDataISO$quar.duration<-as.factor(myDataISO$quar.duration) is.factor(myDataISO$quar.duration) basvs10days<-c(0,1,0,0) # this compares the baseline (prior to quarantine) to a quarantine sub.period of up to 10-days duration basvs50days<-c(0,0,1,0) # this compares the baseline (prior to quarantine) to a quarantine sub.period of up to 50-days duration basvs103days<-c(0,0,0,1) # this compares the baseline (prior to quarantine) to a quarantine sub.period of up to 103-days duration contrasts(myDataISO$quar.duration)<-cbind(basvs10days, basvs50days, basvs103days) myDataISO$quar.duration # To check we setted the contrasts correctly myDataISOIMP2$quar.duration<-as.factor(myDataISOIMP2$quar.duration) is.factor(myDataISOIMP2$quar.duration) basvs10days<-c(0,1,0,0) # this compares the baseline (prior to quarantine) to a quarantine sub.period of up to 10-days duration basvs50days<-c(0,0,1,0) # this compares the baseline (prior to quarantine) to a quarantine sub.period of up to 50-days duration basvs103days<-c(0,0,0,1) # this compares the baseline (prior to quarantine) to a quarantine sub.period of up to 103-days duration contrasts(myDataISOIMP2$quar.duration)<-cbind(basvs10days, basvs50days, basvs103days) myDataISOIMP2$quar.duration # To check we setted the contrasts correctly | Statistical Modeling | https://osf.io/wcqpa/ | Rcode.R |
823 | Calculating effect sizes library(DSUR.noof) We got effect sizes of meaningful predictors by executing: rcontrast(t,df) periodsecond | rcontrast(-2.685100, 97) rcontrast(-5.280908, 1201) | Statistical Test | https://osf.io/wcqpa/ | Rcode.R |
824 | Simulate time varying variable X | data.X = expand.grid(Obs=1:T.obs,ID=1:N.dyad) var.diag.X = c(sigma.XF,sigma.XM) Sigma.X = diag(length(var.diag.X)) Sigma.X[lower.tri(Sigma.X, diag=FALSE)] = rho.X Sigma.X = pmax(Sigma.X, t(Sigma.X), na.rm=TRUE) Sigma.X = diag(var.diag.X)%*%Sigma.X%*%diag(var.diag.X) data.X = cbind(data.X,mvrnorm(N.dyad*T.obs,c(mu.XF,mu.XM),Sigma.X)) colnames(data.X) = c('Obs','ID','X.F','X.M') X.F = data.X[,'X.F'] X.M = data.X[,'X.M'] D.dyad = rbinom(N.dyad*T.obs,1,prob.D) data.X = cbind(data.X,D.dyad) | Data Variable | https://osf.io/vtb9e/ | Sim.Dyad.Model.16.R |
825 | left_join remaining_uncertain_matched to author_data, subset to remove non | author_data <- left_join(author_data, remaining_uncertain_matched, by = c("index" = "index")) author_data$match <- as.integer(author_data$match) | Data Variable | https://osf.io/uhma8/ | apsa_race_ethnicity.R |
826 | remerge (left_join) author_names with author_data | author_data <- left_join(test, author_data, by = c("Contact.apsa", "NameSort.apsa")) %>% subset(duplicated(Contact.apsa) == FALSE) | Data Variable | https://osf.io/uhma8/ | apsa_race_ethnicity.R |
827 | Number of subjects in each group | n.group = c(rep(0,N.0),rep(1,N.1)) n.group = c(rep(0,N.0),rep(1,N.1)) n.group = c(rep(0,N.0),rep(1,N.1)) n.group = c(rep(0,N.0),rep(1,N.1)) | Data Variable | https://osf.io/vguey/ | Sim.Data.IL.R |
828 | Create variables days, beeps per day and Z | data.IL = expand.grid(Time=1:T,Z=n.group) data.IL = expand.grid(Time=1:T,W=W.i) data.IL = expand.grid(Time=1:T,subjno=1:N) data.IL = expand.grid(Time=1:T,subjno=1:N) data.IL = expand.grid(Time=1:T,Z=n.group) data.IL = expand.grid(Time=1:T,Z=n.group) data.IL = expand.grid(Time=1:T,W=W.i) data.IL = expand.grid(Time=1:T,W=W.i) data.IL = expand.grid(Time=1:T,subjno=1:N) data.IL = expand.grid(Time=1:T,Z=n.group) data.IL = expand.grid(Time=1:T,W=W.i) | Data Variable | https://osf.io/vguey/ | Sim.Data.IL.R |
829 | Create variable subjno | subjno = expand.grid(1:T,1:N)[,2] data.IL = cbind(subjno,data.IL) Z = data.IL$Z subjno = expand.grid(1:T,1:N)[,2] data.IL = cbind(subjno,data.IL) W = data.IL$W subjno = expand.grid(1:T,1:N)[,2] data.IL = cbind(subjno,data.IL) Z = data.IL$Z subjno = expand.grid(1:T,1:N)[,2] data.IL = cbind(subjno,data.IL) Z = data.IL$Z subjno = expand.grid(1:T,1:N)[,2] data.IL = cbind(subjno,data.IL) W = data.IL$W subjno = expand.grid(1:T,1:N)[,2] data.IL = cbind(subjno,data.IL) W = data.IL$W subjno = expand.grid(1:T,1:N)[,2] data.IL = cbind(subjno,data.IL) Z = data.IL$Z subjno = expand.grid(1:T,1:N)[,2] data.IL = cbind(subjno,data.IL) W = data.IL$W | Data Variable | https://osf.io/vguey/ | Sim.Data.IL.R |
830 | Create lag Y variable within days for each individual | Ylag = lag.Y(data) data = data.frame(cbind(data,Ylag)) } Ylag = lag.Y(data) data = data.frame(cbind(data,Ylag)) } Ylag = lag.Y(data) data = data.frame(cbind(data,Ylag)) } | Data Variable | https://osf.io/vguey/ | Sim.Data.IL.R |
831 | Parameters of random intercept and random slope are generated from a Beta distribution Parameters of Group0 Stationarity condition: sigma.v1 < sqrt(1b10^2) | if (sigma.v1 > sqrt(1-b10^2)) {stop('To ensure that the model in Group 0 is stationary check that standard deviation of the random slope is smaller than sqrt(1-b10^2) where b10 is the fixed autorregressive effect')} mu.beta.0 = (b10+1)/2 sigma.beta.0 = sigma.v1/2 alpha.beta.0 = mu.beta.0^2*(((1-mu.beta.0)/sigma.beta.0^2) - (1/mu.beta.0)) beta.beta.0 = alpha.beta.0*((1/mu.beta.0) - 1) gamma.01 = rbeta(N.0, alpha.beta.0, beta.beta.0)*2-1 gamma.00 = sigma.v0*(rho.v*scale(gamma.01)+sqrt(1-rho.v^2)*rnorm(N.0)) + rep(b00,N.0) | Statistical Modeling | https://osf.io/vguey/ | Sim.Data.IL.R |
832 | Parameters of random intercept and random slope are generated from a Beta distribution | mu.beta.1 = (b10+b11.W*W.i[i]+1)/2 sigma.beta.1 = sigma.v1/2 alpha.beta.1 = mu.beta.1^2*(((1-mu.beta.1)/sigma.beta.1^2) - (1/mu.beta.1)) beta.beta.1 = alpha.beta.1*((1/mu.beta.1) - 1) gamma.1 = rbeta(1, alpha.beta.1, beta.beta.1)*2-1 gamma.0 = sigma.v0*((rho.v*(gamma.1-(b10+b11.W*W.i[i]))/sigma.v1) + sqrt(1-rho.v^2)*rnorm(1)) + b00+b01.W*W.i[i] if (Ylag.center == TRUE){ AR.epsilon = list(order=c(1,0,0), ar=gamma.1, include.mean = FALSE) Y[which(data.IL$subjno==i)] = arima.sim(n=T,AR.epsilon)*sqrt(1-gamma.1^2)*sigma + gamma.0 } if (Ylag.center == FALSE){ AR.epsilon = list(order=c(1,0,0), ar=gamma.1, include.mean = FALSE) Y[which(data.IL$subjno==i)] = arima.sim(n=T,AR.epsilon)*sqrt(1-gamma.1^2)*sigma + gamma.0/(1-gamma.1) }} | Statistical Modeling | https://osf.io/vguey/ | Sim.Data.IL.R |
833 | Get statistics for observed networks | obs_df <- GetNetStats(group_fit$networks, group_fit$formula, "model") colnames(obs_df) <- stat_labels obs_df <- obs_df %>% mutate(n=1:200, Group=rep(c("Young","Old"), each=100)) %>% melt(measure.vars=stat_labels, variable.name="Stat") obs_df <- rbind(obs_df, data.frame(n=1:200, Group=rep(c("Young","Old"), each=100), Stat = "Local efficiency", value = local_eff), data.frame(n=1:200, Group=rep(c("Young","Old"), each=100), Stat = "Global efficiency", value = global_eff)) sim_df <- obs_df[0, ] young_nets <- group_fit$networks[1:100] for (i in 1:n_sample){ y <- young_nets[[sample(length(young_nets),1)]] myformula <- statnet.common::nonsimp_update.formula(group_fit$formula, y ~., from.new = "y") | Statistical Modeling | https://osf.io/5nh94/ | F8_plot_efficiency_goodness_of_fit.R |
834 | Source functions that allow to easily draw nice visualizations | source("visual_functions_all.R") source("visualize_niceplot.R") | Visualization | https://osf.io/pvyhe/ | exemplar_runs_r_add_xi.R |
835 | Test H1d. "Compliance with behavioural guidelines" by Countries random intercept (country) + the fixed effect of country for all coefficients, priors ~ Cauchy (0, 1) | prior.coef <- brms::prior(cauchy(0,1),class='b') | Statistical Modeling | https://osf.io/z39us/ | Bayesian_analyses_H1d.R |
836 | Calculate total number of language selected by each subj. We will use this to compute a mean weight | sum.home.languages <- adj.home %>% gather(topic2, val, chitchat:gossip) %>% dplyr::group_by(subject, language) %>% dplyr::summarise(n=any(val==1)) %>% dplyr::summarise(n_languages=sum(n)) sum.fam.languages <- adj.fam %>% gather(topic2, val, chitchat:gossip) %>% dplyr::group_by(subject, language) %>% dplyr::summarise(n = any(val == 1)) %>% dplyr::summarise(n_languages=sum(n)) sum.social.languages <- adj.social %>% gather(topic2, val, chitchat:gossip) %>% dplyr::group_by(subject, language) %>% dplyr::summarise(n = any(val == 1)) %>% dplyr::summarise(n_languages=sum(n)) sum.work.languages <- adj.work %>% gather(topic2, val, chitchat:gossip) %>% dplyr::group_by(subject, language) %>% dplyr::summarise(n = any(val == 1)) %>% dplyr::summarise(n_languages=sum(n)) | Data Variable | https://osf.io/6z79s/ | bi.conv.networks.R |
837 | Sum up the adjacency values for each subject for each topictopic pairing, merge with the number of contexts containing responses, and compute mean | sum.adj.home <- adj.home %>% gather(topic2, val, chitchat:gossip) %>% dplyr::group_by(subject, topic,topic2) %>% dplyr::summarise(sum=sum(val)) %>% dplyr::left_join(sum.home.languages) %>% dplyr::mutate(avg=sum/n_languages) %>% ungroup() sum.adj.fam <- adj.fam %>% gather(topic2, val, chitchat:gossip) %>% dplyr::group_by(subject, topic,topic2) %>% dplyr::summarise(sum=sum(val)) %>% dplyr::left_join(sum.fam.languages) %>% dplyr::mutate(avg=sum/n_languages) %>% ungroup() sum.adj.school <- adj.school %>% gather(topic2, val, chitchat:gossip) %>% dplyr::group_by(subject, topic,topic2) %>% dplyr::summarise(sum=sum(val)) %>% dplyr::left_join(sum.school.languages) %>% dplyr::mutate(avg=sum/n_languages) %>% ungroup() sum.adj.social <- adj.social %>% gather(topic2, val, chitchat:gossip) %>% dplyr::group_by(subject, topic,topic2) %>% dplyr::summarise(sum=sum(val)) %>% dplyr::left_join(sum.social.languages) %>% dplyr::mutate(avg=sum/n_languages) %>% ungroup() sum.adj.work <- adj.work %>% gather(topic2, val, chitchat:gossip) %>% dplyr::group_by(subject, topic,topic2) %>% dplyr::summarise(sum=sum(val)) %>% dplyr::left_join(sum.work.languages) %>% dplyr::mutate(avg=sum/n_languages) %>% ungroup() sum.adj.dom <- adj.dom %>% gather(topic2, val, chitchat:gossip) %>% dplyr::group_by(subject, topic,topic2) %>% dplyr::summarise(sum=sum(val)) %>% dplyr::left_join(sum.dom.context) %>% dplyr::mutate(avg=sum/n_context) %>% ungroup() sum.adj.non <- adj.non %>% gather(topic2, val, chitchat:gossip) %>% dplyr::group_by(subject, topic,topic2) %>% dplyr::summarise(sum=sum(val)) %>% dplyr::left_join(sum.non.context) %>% dplyr::mutate(avg=sum/n_context) %>% ungroup() | Data Variable | https://osf.io/6z79s/ | bi.conv.networks.R |
838 | Calculate total number of languages selected by each subj. We will use this to compute a mean weight | sum.school.languages <- adj.school %>% gather(topic2, val, chitchat:gossip) %>% dplyr::group_by(subject, language) %>% dplyr::summarise(n = any(val == 1)) %>% dplyr::summarise(n_languages=sum(n)) | Data Variable | https://osf.io/6z79s/ | bi.conv.networks.R |
839 | NETWORK SIZE (i.e., how many topics are used in each network?) | c.size.long <- contexts.mean %>% select(subject, contains("networkSize")) %>% gather(context, network.size, contains("networkSize")) c.size.long$context = factor(c.size.long$context, levels = c("work.networkSize", "school.networkSize", "home.networkSize", "fam.networkSize", "social.networkSize"), labels = c("Work", "School", "Home", "Family", "Social")) c.size.long = c.size.long %>% filter(!is.na(network.size)) c.size.summary = convenience::sem(c.size.long, dv = network.size, id = subject, context) | Data Variable | https://osf.io/6z79s/ | bi.conv.networks.R |
840 | Calculate total number of contexts selected by each subj. We will use this to compute a mean weight | sum.dom.context <- adj.dom %>% gather(topic2, val, chitchat:gossip) %>% dplyr::group_by(subject, context) %>% dplyr::summarise(n = any(val == 1)) %>% dplyr::summarise(n_context=sum(n)) sum.non.context <- adj.non %>% gather(topic2, val, chitchat:gossip) %>% dplyr::group_by(subject, context) %>% dplyr::summarise(n = any(val == 1)) %>% dplyr::summarise(n_context=sum(n)) | Data Variable | https://osf.io/6z79s/ | bi.conv.networks.R |
841 | Language network stats NETWORK WEIGHT (i.e., how many contexts is each topictopic pair used in this language?) | language.wide <- sum.adj.dom %>% dplyr::full_join(sum.adj.non, by = c("subject", "topic", "topic2")) %>% select(-contains("n_context")) %>% select(-contains("avg")) names(language.wide) <- c("subject","topic", "topic2", "Dominant Language", "Non-dominant Language") language.long <- gather(language.wide, language, weight, "Dominant Language":"Non-dominant Language") language.long = language.long %>% filter(!is.na(weight)) l.weight.summary = convenience::sem(language.long, dv = weight, id = subject, language) language.aov <- aov(weight ~ language, data = language.long) summary.aov(language.aov) # sig*** | Data Variable | https://osf.io/6z79s/ | bi.conv.networks.R |
842 | Mutate targets to uppercase | SPD_all <- SPD_all %>% mutate(target = toupper(target)) dat <- dat %>% mutate(target = toupper(target)) | Data Variable | https://osf.io/wgneh/ | 3 Prepare Data.R |
843 | Compute Zscores separately for each participant and each session | group_by(Subject, Session) %>% mutate(Ztarget.RT = scale(target.RT)) %>% ungroup() %>% | Statistical Test | https://osf.io/wgneh/ | 3 Prepare Data.R |
844 | look up pchange in table based on reward (yes/no) and confidence unselected advisor | sel.row <- subset(p_switch, Reward == reward & Conf.unsel.adv == unselect.adv.conf) sel.row pswitch <- sel.row$Changed pswitch | Data Variable | https://osf.io/9gjyc/ | Simulations Evidence level.R |
845 | exploratory bifactor analysis | fa(resp, fm="ml", cor="tet", nfactors = 5, rotate = "bifactor", correct = 0) | Statistical Modeling | https://osf.io/dkrhy/ | BICBRaschModelsandPlots.R |
846 | estimating Rasch Tree models for gender & age | gender.dif<-raschtree(dat~gender, data=bdat, deriv="numeric", alpha=.01, bonferroni=TRUE) age.dif<-raschtree(dat~age, data=bdat, deriv="numeric", minsize=400, alpha=.01, bonferroni=TRUE) summary(gender.dif) summary(age.dif) plot(gender.dif) plot(age.dif) | Statistical Modeling | https://osf.io/dkrhy/ | BICBRaschModelsandPlots.R |
847 | set those study grades to NA which are outside the range of the grading system | mSI$crt.gru_s_w2[mSI$crt.gru_s_w2 == 0] <- NA mSI$crt.gru_s_w2[mSI$crt.gru_s_w2 > 6] <- NA | Data Variable | https://osf.io/m6pb2/ | Data_preparation_Sample_E.r |
848 | compute and save descriptives statistics of variables before aggregation and standardization | descriptives <- round(select(psych::describe(mSI_descr), n, min, max, mean, sd),2) write.table(descriptives, file="Descriptives/descriptives_Sample_E_mSI.dat", sep="\t") | Data Variable | https://osf.io/m6pb2/ | Data_preparation_Sample_E.r |
849 | mean ratings of targets and decoys by condition | tapply(dat.long$rating, list(dat.long$condition, dat.long$target), mean) tapply(dat.long$rating, list(dat.long$condition, dat.long$target), function(x) sd(x)/sqrt(length(x))) | Data Variable | https://osf.io/eg6w5/ | experiment1d_analyses.R |
850 | paired contrasts on estimated marginal means to unpack interaction | emm_options(lmer.df = "satterthwaite") fitlmer2.em <- emmeans::emmeans(fitlmer2, specs = ~ target*condition | target) fitlmer2.em # estimated marginal means contrast(fitlmer2.em, method = "trt.vs.ctrl", adjust = "none") # paired contrasts with no correction confint(contrast(fitlmer2.em, method = "trt.vs.ctrl", adjust = "none")) # 95% confidence intervals contrast(fitlmer2.em, method = "trt.vs.ctrl", adjust = "holm") # paired contrasts with holm correction s <- as.data.frame(summary(fitlmer2.em)) | Statistical Test | https://osf.io/eg6w5/ | experiment1d_analyses.R |
851 | Statistical tests: ECT Choice score vs Training criteria Did mice reduce their choice score in the test compared to 80% criteria? using JBTxECT_id.csv dataset | wilcox.test(md_id$choice_score[md_id$rat_bedding != "mixed"], mu = 0.6) # 80% big = NCT score 0.6 | Statistical Test | https://osf.io/z6nm8/ | Stats_figures_ECT.R |
852 | Make figures and tables check for correlaitons between individuals | chart.Correlation(ind_res[[14]][,1:6] , histogram=TRUE, pch=19) | Visualization | https://osf.io/rmcuy/ | Model_analysis.R |
853 | define plot styling pp_color for predictive draw lines, set in plotting_style.R | cat("\n\nPlotting posterior predictive checks...\n") cat("Ignore coordinate system and colour warnings;;", "these are expected behavior\n") chains <- rstan::extract(fit) n_checks = length(chains$titer_rep_censored[, 1]) sample_checks = sample(1:n_checks, n_to_plot) print(sample_checks) print(names(chains)) cat(sprintf("\nPlotting pp checks...\n\n")) real_titers <- dat$log10_titer rep_titers <- chains$titer_rep_censored[sample_checks, ] plot_upper <- pp_check(10^(real_titers), yrep = 10^(rep_titers), ## convert to RML titer fun = ppc_dens_overlay, alpha = 0.2) + ggtitle("Predictive checks") + scale_color_manual(name="", labels = c("real data", "posterior predictive draws"), values = c("black", pp_color)) + scale_x_continuous( trans = 'log10', labels = trans_format('log10', math_format(10^.x))) + coord_cartesian(xlim = c(10^0.5, 10^6.5)) + expand_limits(x = 0.5, y = 0) + theme_project(base_size = 30) | Visualization | https://osf.io/fb5tw/ | figure_pp_check.R |
854 | extract relevant data & calculate Brier score for each participant | lay.data <- NULL for (i in 1:nsubjects) { study.order <- as.numeric(unlist(strsplit(prediction.data$preorder[i], split="|", fixed = TRUE)))[2:28] label <- ifelse(prediction.data$Conditie[i]==1,"des.","bf.") subject.data <- NULL for (j in 1:nstudies){ understanding <- eval(parse(text = paste0("prediction.data$`",study.order[j],"_",label,"0`" )))[i] # 1 = did not understand, otherwise: NA replication.belief <- eval(parse(text = paste0("prediction.data$`",study.order[j],"_",label,"belief`" )))[i] - 1 # now 0 = will not be replicated, 1 = will be replicated confidence.rating <- eval(parse(text = paste0("prediction.data$`",study.order[j],"_",label,"conf_1`")))[i] # on a scale from 0 - 100 confidence.rating <- ifelse(replication.belief == 0, confidence.rating*-1, confidence.rating) # make confidence in replication failure negative confidence.rating <- confidence.rating / 200 + .5 # convert to 0-1 scale study <- j condition <- ifelse(label == "des.","DescriptionOnly","DescriptionPlusStatistics") replication.outcome <- replication.outcomes[j] replication.effectsize <- replication.effectsizes[j] ind.subject.data <- cbind(study,condition,understanding,replication.belief,confidence.rating, replication.outcome,replication.effectsize) subject.data <- rbind(subject.data,ind.subject.data) } subject <- i ind.lay.data <- cbind(subject,subject.data) lay.data <- rbind(lay.data,ind.lay.data) } rm(study.order,label,condition,subject.data,understanding,replication.belief,confidence.rating, i,j,study,replication.outcome,replication.effectsize,ind.subject.data,subject,ind.lay.data) | Data Variable | https://osf.io/x72cy/ | PreprocessingQualtricsData.R |
855 | 3. Data exclusion based on set criteria criteria: 1. if participants failed the attention check (i.e., did not press 'NO' and 75% (range 7080 is allowed)) 2. if a study description is not understood, exlcude this study for this participant 3. if a study is not understood by > 50% of the participants, exclude this study 4. if a participant does not understand > 50% of the studies, exclude this participant | bogus.study <- 27 clean.data <- as.data.frame(lay.data, stringsAsFactors = FALSE) correct.range <- clean.data[clean.data$study==bogus.study,]$confidence.rating correct.range <- rep(correct.range >= .1 & correct.range <= .15, each = nstudies) # correct range NO and 70-80% --> .1-.15 on the confidence scale clean.data.1 <- clean.data[correct.range,] # apply 1. clean.data.2 <- clean.data.1[is.na(clean.data.1$understanding),] # apply 2. remove.studies <- which(table(clean.data.2$study)<nsubjects/2) # indicate which studies are understood by less than half of the people clean.data.3 <- clean.data.2[! clean.data.2$study %in% remove.studies,] # apply 3. remove.subjects <- which(table(clean.data.3$subject)<nstudies/2) # indicate which subjects understood less than half of the studies clean.data.4 <- clean.data.3[! clean.data.3$subject %in% remove.subjects,] # apply 4. full.data <- clean.data.4 full.data$understanding <- NULL # delete empty column | Data Variable | https://osf.io/x72cy/ | PreprocessingQualtricsData.R |
856 | total_distance of roads surveyed | sum(unique(site_data_cleaned$Site_Length_m)) | Data Variable | https://osf.io/82dqk/ | PublicationCode2.R |
857 | Bring in census data for each site. | census_data <- fread("StudyAreas/Demographic_Site_Data/PDB_2015_Tract.csv") | Data Variable | https://osf.io/82dqk/ | PublicationCode2.R |
858 | Plot Quantiles against one another. | p2 <- ggplot() + geom_point(aes(y = receipt_distance_quantiles, x = montecarlo_distance_quantiles)) + geom_smooth(aes(y = receipt_distance_quantiles, x = montecarlo_distance_quantiles), method = "lm", se = F) + scale_x_log10(breaks= 10^c(1:5)) + scale_y_log10() + theme_classic(base_size = 20) + labs(x = "Human Trip Quantile Distance (m)", y = "Receipt Quantile Distance (m)") + coord_equal() + geom_abline(intercept = 0, slope = 1) | Visualization | https://osf.io/82dqk/ | PublicationCode2.R |
859 | join the trash bearing data and wind data into single frame for plotting. | CompleteDataCoordPlot <- CompleteDataWithGoogle %>% filter(!is.na(windxcoordmeanbearing) & !is.na(trashxcoordbearing)) %>% #Removes data where we don't have wind or dont have receipt direction from the analysis. dplyr::select(windxcoordmeanbearing, windycoordmeanbearing, row) %>% rename(x = windxcoordmeanbearing, y = windycoordmeanbearing) %>% bind_rows(CompleteDataWithGoogle %>% filter(!is.na(windxcoordmeanbearing) & !is.na(trashxcoordbearing)) %>% dplyr::select(trashycoordbearing, trashxcoordbearing, row) %>% rename(x = trashycoordbearing, y = trashxcoordbearing)) | Data Variable | https://osf.io/82dqk/ | PublicationCode2.R |
860 | Check if Trial column exists, if not create it | if (!"Trial" %in% colnames(df)) { df <- cbind(Trial = NA, df) } trial_counter <- 1 for (i in seq_along(index_pairs$start)) { start_pos <- index_pairs$start[i] end_pos <- index_pairs$end[i] | Data Variable | https://osf.io/yfegm/ | allocateTrials.r |
861 | group level Pi/Pb for each set size on probability scale | PiIdx <- NULL for (j in 1:nsubj) PiIdx <- c(PiIdx, which(names(as.data.frame(mcmcChain)) == paste0("Pi[", j, ",", s, "]"))) PbIdx <- NULL for (j in 1:nsubj) PbIdx <- c(PbIdx, which(names(as.data.frame(mcmcChain)) == paste0("Pb[", j, ",", s, "]"))) meanPi[s,experiment,] <- rowMeans(mcmcChain[, PiIdx]) # means across subjects of posterior means of Pi for each set size meanPb[s,experiment,] <- rowMeans(mcmcChain[, PbIdx]) } DeltaPi[,experiment] <- mcmcChain[, paste0("dPi")] # posterior samples of slope of Pi over set size DeltaPb[,experiment] <- mcmcChain[, paste0("dPb")] print(colMeans(DeltaPi>0)) # proportion of posterior samples > 0 save(MuPi, MuPb, meanPi, meanPb, DeltaPi, DeltaPb, file=parChainFile) } | Statistical Modeling | https://osf.io/qy5sd/ | PairsBindingRSS_MPT.R |
862 | determine manifestations and visualize cultural value dimensions | d$SVS_d1 <- d$SVS_harmony - d$SVS_mastery d$SVS_d2 <- d$SVS_egalit - d$SVS_hierarchy d$SVS_d3 <- (d$SVS_autona+d$SVS_autoni)/2 - d$SVS_embed cor(d[grepl("_d",names(d))]) f$SVS_d1 <- f$SVS_harmony - f$SVS_mastery f$SVS_d2 <- f$SVS_egalit - f$SVS_hierarchy f$SVS_d3 <- (f$SVS_autona+f$SVS_autoni)/2 - f$SVS_embed cor(f[grepl("_d",names(f))]) pcf <- princomp(f[,3:9], cor=T) summary(pcf) loadings(pcf) | Visualization | https://osf.io/qxf5t/ | TSST_Meta.R |
863 | CTRees analyze the trees for each agreement indicator individually: Variationcorrelation of reported likelihood ~ proportion unstable: | png("output/figures/paper/ctree_rhopsi.png", width = 600, height = 350) VS_ <- VS VS_ <- VS_[!is.na(VS_$rho_llhd) & !is.na(VS_$lagZ_20), ] VS_ <- VS_[!VS_$gtype_class %in% c("IFrc", "IFsc", "MFcr", "FCxr") & VS_$band == "TL", ] VS_$gtype_class[VS_$gtype_class %in% "SH" & VS_$gtype_rank == "secondary"] <- "SH/FC" CT <- partykit::ctree(rho_llhd ~ nPDays , data = VS_, alpha = 0.05, maxdepth = 2) Vars <- setVars4ctreeColoring(VS_) plotCTree(CT) dev.off() | Statistical Modeling | https://osf.io/w7pjy/ | analyze_agreementIndicators.R |
864 | Selecting and recoding items that were measured in all waves | d <- df %>% select(id, wave, lsat = sat6, fsat = sat1i3, per1i2, per1i7, per1i13) %>% mutate(per1i2 = invert(per1i2, 5)) | Data Variable | https://osf.io/fdp39/ | functions.r |
865 | 6. Extract & plot estimates Is evolution more comparable to B0 or B1? | describe_posterior((r.delta.z[,1,])) # B0_Conc describe_posterior((r.delta.z[,2,])) # B0_Disc describe_posterior((r.delta.z[,3,])) # B1_Conc describe_posterior((r.delta.z[,4,])) # B1_Disc | Visualization | https://osf.io/pnug5/ | 2.Ginteger_CrossSex_skewers.R |
866 | for each subject, aggregate his/her selfratings across all interactions (in second and third week of eventbased assessment) | app_SR_aggr <- aggregate(app_SR, by=list(app_SR$id_a), mean) | Data Variable | https://osf.io/m6pb2/ | Data_preparation_Sample_C.R |
867 | recode abitur grades which were not provided but stored as 0, and grades that were provided in units of the wrong grading system | surv2345$abitur_grade[surv2345$abitur_grade == 0] <- NA surv2345$abitur_grade[surv2345$abitur_grade == 12] <- 2.0 surv2345$abitur_grade[surv2345$abitur_grade == 13] <- 1.7 | Data Variable | https://osf.io/m6pb2/ | Data_preparation_Sample_C.R |
868 | define a function which, for each person, selects the first nonNA measurement he provided out of three time points ( out of three variables) | firstnonNA_3timepoints <- function(df) {if(all(is.na(df))){ NA } else if (!is.na(df[1])){ df[1] } else if (!is.na(df[2])){ df[2] } else if (!is.na(df[3])){ df[3] } } | Data Variable | https://osf.io/m6pb2/ | Data_preparation_Sample_C.R |
869 | for the exam grades 15 to 18 which have been assessed only at the last occasions (Survey 5), save the grade in new variable for consistency in notation | surv2345$retro_grades_15 <- surv2345$retro_grades_15_t5 surv2345$retro_grades_16 <- surv2345$retro_grades_16_t5 surv2345$retro_grades_17 <- surv2345$retro_grades_17_t5 surv2345$retro_grades_18 <- surv2345$retro_grades_18_t5 | Data Variable | https://osf.io/m6pb2/ | Data_preparation_Sample_C.R |
870 | select variables (all 18 exam grades) to be aggregated for mean exam grade | retro_grades_df <- as.matrix(surv2345[,paste0("retro_grades_",1:18)]) | Data Variable | https://osf.io/m6pb2/ | Data_preparation_Sample_C.R |
871 | Select variables for the analyses and save data frame that will be uploaded in the OSF | connect_osf <- select(connect, Z_Raven_self:Z_MWTB_obj, Z_global_selfeval:Z_achievement) write.table(connect_osf, file="Data_Sample_C_connect.txt",sep = "\t",col.names=TRUE) | Data Variable | https://osf.io/m6pb2/ | Data_preparation_Sample_C.R |
872 | DESCRIPTIVE STATISTICS compute and save sample statistics (age distribution, number of females) | age <- round(select(psych::describe(connect_descr$age), n, min, max, mean, sd),2) age$n <- nrow(connect_descr) sampstats <- mutate(age, female=plyr::count(connect_descr$sex)[plyr::count(connect_descr$sex)[,1]=="1",]["freq"] ) write.table(sampstats, file="Descriptives/age_sex_Sample_C_connect.dat", sep="\t", row.names=FALSE) | Data Variable | https://osf.io/m6pb2/ | Data_preparation_Sample_C.R |
873 | compute and save correlation table of variables before aggregation and standardization | cor_raw <- corcons(connect_descr) write.table(cor_raw, file="Descriptives/correlations_raw_Sample_C_connect.dat", sep="\t") | Data Variable | https://osf.io/m6pb2/ | Data_preparation_Sample_C.R |
874 | Hypothesis 1.1 Hypothesis 1 was tested via pairedsample t.tests (alphas need to be Bonferronicorrected) Examples for conscientious goal classes (first two rows of Table 1 Conscientious Goals). Remaining tests are simialr | t.test(x = dt1$CP_Class_01, y = dt1$CN_Class_01, paired = TRUE, alternative = "greater") t.test(x = dt1$CP_Class_02, y = dt1$CN_Class_02, paired = TRUE, alternative = "greater") | Statistical Test | https://osf.io/ywm3r/ | Analyses.R |
875 | Hypothesis 1.2 Hypothesis 1.2 was tested via partiallyoverlapping samples ttests. We report the analyses for the first panel of Table S2 (and for pvalues reported in Table 2). The remaining analyses are identical, but were performed on other goal classes | Partover.test(dt1$CP_Class_01, dt1$HP_Class_01, stacked = TRUE, alternative = "greater") Partover.test(dt1$CP_Class_01, dt1$EP_Class_01, stacked = TRUE, alternative = "greater") Partover.test(dt1$CP_Class_01, dt1$XP_Class_01, stacked = TRUE, alternative = "greater") Partover.test(dt1$CP_Class_01, dt1$AP_Class_01, stacked = TRUE, alternative = "greater") Partover.test(dt1$CP_Class_01, dt1$OP_Class_01, stacked = TRUE, alternative = "greater") Partover.test(dt1$CP_Class_01, dt1$HN_Class_01, stacked = TRUE, alternative = "greater") Partover.test(dt1$CP_Class_01, dt1$EN_Class_01, stacked = TRUE, alternative = "greater") Partover.test(dt1$CP_Class_01, dt1$XN_Class_01, stacked = TRUE, alternative = "greater") Partover.test(dt1$CP_Class_01, dt1$AN_Class_01, stacked = TRUE, alternative = "greater") Partover.test(dt1$CP_Class_01, dt1$ON_Class_01, stacked = TRUE, alternative = "greater") | Statistical Test | https://osf.io/ywm3r/ | Analyses.R |
876 | Examples of Tobit regressions of the subjective importance of specific goals on HEXACO traits (first two lines of Table 3). Pvalues need to be corrected using the Bonferroni method, considering that we performed 21 multiple regressions (multiply them by 21 and round values larger than 1 to 1) | predictors <- select(dt2, HEXACO_H:HEXACO_O) %>% scale() fit1 <- censReg(dt2$G_C_01_DimostrareQlcQln_Importance ~ predictors, left = 1, right = 9) summary(fit1) fit2 <- censReg(dt2$G_C_02_EssereDegnoFiducia_Importance ~ predictors, left = 1, right = 9) summary(fit2) | Statistical Modeling | https://osf.io/ywm3r/ | Analyses.R |
877 | Hierarchical regression predicting the willingness to change conscientiousness according to CBFI (Table 4). For ease of formatting, I used the R package AutoModel | Data4HierarchicalReg <- select(dt2, CBFI_C, POS, HEXACO_H:HEXACO_O, BFI2_O:BFI2_N, Importance_GC, Importance_GU) %>% scale() %>% data.frame() Data4HierarchicalReg$BFTGI_C_bin <- as.numeric(dt2$BFTGI_C == 3) | Statistical Modeling | https://osf.io/ywm3r/ | Analyses.R |
878 | Hypothesis 3.2 multiple regressions predicting each goal class from HEXACO traits (we report examples reproducing the first two rows of Table 8, the code for the others is similar, save for the goal class). Pvalues need to be corrected using the Bonferroni method, considering 9 multiple regressions (multiply them by 9 and transform values > 1 to 1) | lm(G08Rules ~ ., data = select(dt3, G08Rules, HEXACO_H:HEXACO_O)) %>% lm.beta %>% summary lm(G10Control ~ ., data = select(dt3, G10Control, HEXACO_H:HEXACO_O)) %>% lm.beta %>% summary | Statistical Modeling | https://osf.io/ywm3r/ | Analyses.R |
879 | DIFFERENTIAL ITEM FUNCTIONING Create trichotomous income variable | data = data %>% mutate( income3 = recode(income, '1=1;; 2=1;; 3=1;; 4=1;; 5=1;; 6=1;; 7=1;; 8=1;; 9=2;; 10=2;; 11=2;; 12=2;; 13=2;; 14=3;; 15=3;; 16=3;; 17=3;; 18=3')) q1merit = data[c("Q1A", "Q1B", "Q1H", "Q1N")] q1opportunity = data[c("Q1C", "Q1D", "Q1F", "Q1G")] q1chance = data[c("Q1I", "Q1O", "Q1P", "Q1Q")] q2merit = data[c("Q2A", "Q2B", "Q2H", "Q2N")] q2opportunity = data[c("Q2C", "Q2D", "Q2F", "Q2G")] q2chance = data[c("Q2I", "Q2O", "Q2Q", "Q2R")] q3merit = data[c("Q3A", "Q3B", "Q3H", "Q3N")] q3opportunity = data[c("Q3C", "Q3D", "Q3F", "Q3G")] q3chance = data[c("Q3I", "Q3O", "Q3P", "Q3Q")] q4merit = data[c("Q4B", "Q4C", "Q4I", "Q4N")] q4opportunity = data[c("Q4D", "Q4E", "Q4G", "Q4H")] q4chance = data[c("Q4J", "Q4O", "Q4P", "Q4Q")] sesmerit = data[c("hs_merit", "ls_merit", "ha_merit", "la_merit")] sesopportunity = data[c("hs_opportunity", "ls_opportunity", "ha_opportunity", "la_opportunity")] seschance = data[c("hs_chance", "ls_chance", "ha_chance", "la_chance")] merit_full = data[c("hs_efft", "hs_abil", "ls_efft", "ls_abil", "ha_efft", "la_efft")] gender = data$gender age = data$AGE4 politic = data$D3 income = data$income3 educ = data$EDUC4 | Data Variable | https://osf.io/25a6x/ | BeliefsScale_IRT_Rscript.R |
880 | Display distribution of efficacy judgments (can be used to set a prior on the next experiment) | eff_all <- c(eff_nograph, eff_graph) par(mfrow=c(2,3)) myhist("Efficacy", eff_all, 1, 9, N/2) myhist("Efficacy - no graph", eff_nograph, 1, 9, N/4) myhist("Efficacy - graph", eff_graph, 1, 9, N/4) cat("Grand mean for efficacy: ", format_number(mean(eff_all)), "\n") | Visualization | https://osf.io/zh3f4/ | exp1 simulated analysis.R |
881 | Models by social network measure 1. Indegree | m1 <- glmer(pup_year_surv~indegree + valley + overall.index + pup_sex + pup_littersizeborn + mother_age + network_size + pup_emerjdate + overall.index*indegree + valley*indegree + (1|mother_uid) + (1|pup_yrborn), control = glmerControl("bobyqa", optCtrl=list(maxfun=2e5)), data=sur_data, family= binomial) summary(m1) | Data Variable | https://osf.io/wc3nq/ | 7) agr_yearly_model.R |
882 | remove upper triangle of correlation matrix | if(removeTriangle[1]=="upper"){ Rnew <- as.matrix(Rnew) Rnew[upper.tri(Rnew, diag = TRUE)] <- "" Rnew <- as.data.frame(Rnew) } | Data Variable | https://osf.io/3b59h/ | Analysis.R |
883 | put SDs in parantheses | mutate(gender_sd = paste0("(", gender_sd, ")"), age_sd = paste0("(", age_sd, ")"), parent_sd = paste0("(", parent_sd, ")"), pol_sd = paste0("(", pol_sd, ")")) %>% mutate(gender_sd = paste0("(", gender_sd, ")"), age_sd = paste0("(", age_sd, ")"), parent_sd = paste0("(", parent_sd, ")"), pol_sd = paste0("(", pol_sd, ")")) %>% mutate(intent_apply_job_sd = paste0("(", intent_apply_job_sd, ")"), intent_apply_ps_sd = paste0("(", intent_apply_ps_sd, ")"), psm_sd = paste0("(", psm_sd, ")"), pofit_sd = paste0("(", pofit_sd, ")"), pjfit_sd = paste0("(", pjfit_sd, ")")) %>% mutate(intent_apply_job_sd = paste0("(", intent_apply_job_sd, ")"), intent_apply_ps_sd = paste0("(", intent_apply_ps_sd, ")"), psm_sd = paste0("(", psm_sd, ")"), pofit_sd = paste0("(", pofit_sd, ")"), pjfit_sd = paste0("(", pjfit_sd, ")")) %>% | Data Variable | https://osf.io/3b59h/ | Analysis.R |
884 | 5.3 Pirateplot for dependent variables | df_pirate_dv <- tibble(dv = c(df$intent_apply_job, df$intent_apply_ps), group = c(rep.int(0, length(df$intent_apply_job)), rep.int(1, length(df$intent_apply_ps)))) %>% mutate(group = factor(group, labels = c("Intention to\napply for job", "Intention to apply\nfor public service"))) pirate_dvs <- yarrr::pirateplot(dv ~ group, data = df_pirate_dv, inf.method = "ci", xlab = "Dependent variable", ylab = "", theme = 2, cex.lab = 1.2, cex.axis = 1.2, cex.names = 1.2) pirate_dvs <- recordPlot() # contains all plotting information png("./output/Appendix_pirate_dvs.png") pirate_dvs dev.off() | Visualization | https://osf.io/3b59h/ | Analysis.R |
885 | Load the functions for the raincloud plots | source('funcs/R_rainclouds.R') | Visualization | https://osf.io/4fvwe/ | load_my_functions.R |
886 | Save the result and load if you run the permutation test on a different computer than the visualizations | save(list.res,file="results.Rdata") load("results.Rdata") | Visualization | https://osf.io/greqt/ | 02_analysis.R |
887 | data as a scatter plot, column s for x and column v for y, size 4 points, use the sat_curve data frame as the source | geom_point(data = sat_curve, aes(x = s, y = v), size = 4) + | Visualization | https://osf.io/9e3cu/ | sat_curve.R |
888 | fit as a line plot, use the mm_fit data frame as the data source | geom_line(data = mm_fit, aes(x = s, y = v)) + | Visualization | https://osf.io/9e3cu/ | sat_curve.R |
889 | change the axis label text to size 22, bold, and black color | axis.text.x = element_text(size = 22, face = "bold", color = "black"), axis.text.y = element_text(size = 22, face = "bold", color = "black")) + | Visualization | https://osf.io/9e3cu/ | sat_curve.R |
890 | sequence of age inputs within range of model: (15, 75) years old | seq.length <- length(seq(15, 75, 1)) | Data Variable | https://osf.io/92e6c/ | analyze_scan_model_hadza.R |
891 | Define link function with softmax transformation The following function is taken from Koster and McElreath (2017) Modifications made to accommodate current model structure (e.g. addition of com_id, month) | link.mn <- function( data ) { K <- dim(post$v_id)[3] + 1 ns <- dim(post$v_id)[1] if ( missing(data) ) stop( "BOOM: Need data argument" ) n <- seq.length softmax2 <- function(x) { x <- max(x) - x exp(-x)/sum(exp(-x)) } p <- list() for ( i in 1:n ) { p[[i]] <- sapply( 1:K , function(k) { if ( k < K ) { ptemp <- post$a[,k] + post$bA[,k] * data$age_z[i] + post$bQ[,k] * data$age_zq[i] + post$bT[,k] * data$time_z[i] + post$bTQ[,k] * data$time_zq[i] if ( data$id[i]>0 ) ptemp <- ptemp + post$v_id[,data$id[i],k] if ( data$com_id[i]>0 ) ptemp <- ptemp + post$v_com[,data$com_id[i],k] if ( data$month_id[i]>0 ) ptemp <- ptemp + post$v_month[,data$month_id[i],k] } else { ptemp <- rep(0,ns) } return(ptemp) }) | Statistical Modeling | https://osf.io/92e6c/ | analyze_scan_model_hadza.R |
892 | The values are converted to probabilities using the softmax function which ensures that the predicted values across categories sum to 100% probabilities. | for ( s in 1:ns ) p[[i]][s,] <- softmax2( p[[i]][s,] ) } return(p) } for ( s in 1:ns ) p[[i]][s,] <- softmax2( p[[i]][s,] ) } return(p) } low_age <- (15 - mean_age_female)/sd_age_female high_age <- (75 - mean_age_female)/sd_age_female | Statistical Modeling | https://osf.io/92e6c/ | analyze_scan_model_hadza.R |
893 | everything will be calculated over the "adult" interval from 15 to 75 | age_seq <- (seq(15, 75, 1)- mean_age_female)/sd_age_female | Data Variable | https://osf.io/92e6c/ | analyze_scan_model_hadza.R |
894 | We create a data frame from age_seq and its second order polynomial, holding most of predictors at their sample mean. In the original Koster+McElreath paper, they specified 8:00 am for the time of day in order to effect a more sensible alignment with the empirical data. In this case, we hold that parameter at 0, which therefore corresponds with the mean time of day in our dataset for behavioral observations (0.532 ~12:45). Also, as we noted earlier in the notes about the multinomial link function, we set "id" to zero in order to average over the random effects. | pred_dat <- data.frame( id = 0 , age_z = age_seq, age_zq = age_seq^2, time_z = 0, time_zq = 0, com_id = 0, month_id = 0 ) p <- link.mn ( pred_dat ) | Statistical Modeling | https://osf.io/92e6c/ | analyze_scan_model_hadza.R |
895 | Biodiversity conversion general form is Index (Maxent ^ wM + Abundance ^ wL )^(1/(wM+wL)) but would need to take care of how this scales | pro.fun <- function(x, abuntab, zonename){ (x^wM*abuntab[,which(names(abuntab)==zonename)]^wL)^(1/(wM+wL))} | Statistical Modeling | https://osf.io/5ejcq/ | data_preperation_functions.R |
896 | Construct variable for number of family members in country | famcountry = data4$partnerwhere + data4$mumwhere + data4$dadwhere table(famcountry) data4$famcountry <- famcountry hist(data4$famcountry) sum(is.na(data4$famcountry)) #175 | Data Variable | https://osf.io/qjfv4/ | refugeeservice_varwork2.R |
897 | Plot network latent variable on CFA latent variable | layout(t(c(1,2))) plot(cfaLV, netLV, main = "Network Latent Variable\non CFA Latent Variable", ylab = "Network Latent Variable", xlab = "CFA Latent Variable") | Visualization | https://osf.io/5hpjn/ | NetworkToolbox.R |
898 | Plot participant means on CFA latent variable | plot(cfaLV, pmeans, main = "Participant Means on\nCFA Latent Variable", ylab = "Participant Means", xlab = "CFA Latent Variable") | Visualization | https://osf.io/5hpjn/ | NetworkToolbox.R |
899 | initialize matrices to store validation results | WklValidation <- matrix(nrow = nrow_max, ncol = 13, dimnames = list(seq(nrow_max), c("distribution", "nProfiles_checked", "day_after_burial", "timewindow_lower", "timewindow_upper", "likelihood_reported", "likelihoodSpread_reported", "distribution_reported", "sensitivity_reported", "size_reported", "sizeSpread_reported", "grain_size_reported", "data_quality"))) WklValidation_char <- matrix(nrow = nrow_max, ncol = 10, dimnames = list(seq(nrow_max), c("vf_uuid", "pwl_uuid", "pwl", "validation_date", "band", "timing_mode", "gtype_class", "gtype_rank", "comment", "danger_rating"))) vf_uuid <- NA | Data Variable | https://osf.io/w7pjy/ | PWLcapturedByModel.R |
900 | run linear models on predicted probabilities, to calculate the trend | models <- pred %>% group_by(x, country) %>% nest() %>% mutate(models = map(data, ~ lm(predicted ~ wave, data = .))) %>% spread_coef(models, se = TRUE) | Statistical Modeling | https://osf.io/7wd8e/ | 06 - Trends.R |
Subsets and Splits