### Load the BayesFactor Package in R Source: https://richarddmorey.github.io/BayesFactor Use the 'library' function to load the BayesFactor package after installation. This makes all package functions available for use. ```r library(BayesFactor) ``` -------------------------------- ### Comparing Specific Linear Models with lmBF Source: https://richarddmorey.github.io/BayesFactor Use lmBF to compare a small number of specific models. This example compares a model with 'complaints' to one with 'complaints' and 'learning'. ```R complaintsOnlyBf = lmBF(rating ~ complaints, data = attitude) complaintsLearningBf = lmBF(rating ~ complaints + learning, data = attitude) ## Compare the two models complaintsOnlyBf / complaintsLearningBf ``` -------------------------------- ### Bottom-Up Bayes Factor Analysis Source: https://richarddmorey.github.io/BayesFactor Perform a 'bottom-up' Bayes factor analysis to compare models starting from the simplest. Requires specifying whichModels to 'bottom'. ```R bf = regressionBF(rating ~ ., data = attitude, whichModels = "bottom") plot(bf) ``` -------------------------------- ### Linear Model with Mixed Covariates Source: https://richarddmorey.github.io/BayesFactor Use lmBF to model relationships with both continuous and categorical covariates. This example uses log2 of dose and includes interaction terms. ```R data(ToothGrowth) # model log2 of dose instead of dose directly ToothGrowth$dose = log2(ToothGrowth$dose) # Classical analysis for comparison lmToothGrowth <- lm(len ~ supp + dose + supp:dose, data=ToothGrowth) summary(lmToothGrowth) ``` -------------------------------- ### Protecting terms from exclusion in generalTestBF Source: https://richarddmorey.github.io/BayesFactor Use the neverExclude argument to ensure specific model terms are always included. This example demonstrates how to keep the ID term in the model. ```R puzzleGenBF <- generalTestBF(RT ~ shape + color + shape:color + shape:ID + ID, data=puzzles, whichRandom="ID", neverExclude="ID") puzzleGenBF ``` -------------------------------- ### Get the Number of Model Comparisons Source: https://richarddmorey.github.io/BayesFactor The `length` function can be used to determine the total number of model comparisons computed by `regressionBF`. ```R length(bf) ``` -------------------------------- ### Sample Posterior Distribution for Meta-analytic t-test Source: https://richarddmorey.github.io/BayesFactor Obtain posterior samples for the standardized effect size (delta) from a meta-analytic Bayes factor analysis using the posterior function. Ensure the analysis is performed without a nullInterval restriction to get unrestricted samples. ```r bf = meta.ttestBF(t=t, n1=N, rscale=1) ## Obtain posterior samples chains = posterior(bf, iterations = 10000) ``` ```r plot(chains) ``` -------------------------------- ### Summarize ANOVA Model for ToothGrowth Data Source: https://richarddmorey.github.io/BayesFactor Prepare the ToothGrowth data by treating 'dose' as a factor and then fit an ANOVA model using aov. The summary provides details on the effects of supplement type, dose, and their interaction. ```r ToothGrowth$dose = factor(ToothGrowth$dose) levels(ToothGrowth$dose) = c("Low", "Medium", "High") summary(aov(len ~ supp*dose, data=ToothGrowth)) ``` -------------------------------- ### Compare Best Models to the Overall Best Source: https://richarddmorey.github.io/BayesFactor Divide the Bayes factors of the top models by the maximum Bayes factor to compare them relative to the best model. ```R bf2 = head(bf) / max(bf) ``` -------------------------------- ### Compute Posterior Parameter Estimates (No Interaction Model) Source: https://richarddmorey.github.io/BayesFactor Sample from the no-interaction model using the posterior function to examine its parameter estimates. Summarize the first five parameters. ```R chainsNoInt <- posterior(noInteraction, iterations = 10000) # summary of the "interesting" parameters summary(chainsNoInt[,1:5]) ``` -------------------------------- ### Summarize Posterior Samples Source: https://richarddmorey.github.io/BayesFactor Provides a summary of the posterior samples, including empirical mean, standard deviation, and quantiles for the 'rho' (correlation) and 'zeta' parameters. This helps in understanding the estimated correlation and its uncertainty. ```R summary(samples) ``` -------------------------------- ### Posterior Sampling Summary Source: https://richarddmorey.github.io/BayesFactor Summary statistics from posterior sampling, including mean, standard deviation, and quantiles for model parameters. ```R ## ## Iterations = 1:10000 ## Thinning interval = 1 ## Number of chains = 1 ## Sample size per chain = 10000 ## ## 1. Empirical mean and standard deviation for each variable, ## plus standard error of the mean: ## ## Mean SD Naive SE Time-series SE ## mu 64.619 1.305 0.01305 0.01305 ## complaints 0.609 0.127 0.00127 0.00133 ## learning 0.201 0.139 0.00139 0.00139 ## sig2 52.019 15.768 0.15768 0.19387 ## g 1.972 7.349 0.07349 0.07611 ## ## 2. Quantiles for each variable: ## ## 2.5% 25% 50% 75% 97.5% ## mu 62.0398 63.758 64.627 65.487 67.171 ## complaints 0.3572 0.526 0.610 0.694 0.856 ## learning -0.0749 0.110 0.202 0.293 0.472 ## sig2 29.6847 41.015 49.551 59.708 90.126 ## g 0.1672 0.457 0.840 1.679 9.252 ``` -------------------------------- ### View the Worst Models Source: https://richarddmorey.github.io/BayesFactor Use `tail(bf, n=4)` to display the 4 models with the lowest Bayes factors. ```R tail(bf, n=4) ``` -------------------------------- ### View the Best Models Source: https://richarddmorey.github.io/BayesFactor Use `head(bf, n=6)` to display the top 6 models with the highest Bayes factors. ```R head(bf, n=6) ``` -------------------------------- ### Compare ANOVA Models with Bayes Factors Source: https://richarddmorey.github.io/BayesFactor Compares different ANOVA models for the ToothGrowth dataset by calculating Bayes factors. Models are concatenated and compared against the null intercept-only model. The best model is identified by comparing Bayes factors. ```R ToothGrowth$doseAsFactor <- factor(ToothGrowth$dose) levels(ToothGrowth$doseAsFactor) <- c(.5,1,2) aovBFs <- anovaBF(len ~ doseAsFactor + supp + doseAsFactor:supp, data = ToothGrowth) ``` ```R allBFs <- c(aovBFs, full, noInteraction, onlyDose) ## eliminate the supp-only model, since it performs so badly allBFs <- allBFs[-1] ## Compare to best model allBFs / max(allBFs) ``` -------------------------------- ### Plot Posterior Distributions Source: https://richarddmorey.github.io/BayesFactor Visualizes the posterior distributions for selected model parameters. ```R plot(chains[,4:6]) ``` -------------------------------- ### Sample MCMC Chain Parameters with lmBF Source: https://richarddmorey.github.io/BayesFactor Obtain MCMC chains for a linear model using lmBF. Set noSample=TRUE to view parameter names without performing sampling, useful for inspecting model structure. ```R data(puzzles) # Get MCMC chains corresponding to "full" model # We prevent sampling so we can see the parameter names # iterations argument is necessary, but not used fullModel = lmBF(RT ~ shape + color + shape:color + ID, data = puzzles, noSample=TRUE, posterior = TRUE, iterations=3) ``` ```R fullModel ``` -------------------------------- ### Compute Posterior Parameter Estimates (Full Model) Source: https://richarddmorey.github.io/BayesFactor Use the posterior function to obtain parameter estimates from a fitted model. Specify the number of iterations for the MCMC sampling. Summarize the 'interesting' parameters. ```R chainsFull <- posterior(full, iterations = 10000) # summary of the "interesting" parameters summary(chainsFull[,1:7]) ``` -------------------------------- ### Prepare Data for Two-Sample T-test Source: https://richarddmorey.github.io/BayesFactor Prepare the `chickwts` dataset for a two-sample t-test by restricting it to two specific groups and dropping unused factor levels. ```R data(chickwts) ## Restrict to two groups chickwts = chickwts[chickwts$feed %in% c("horsebean","linseed"),] ## Drop unused factor levels chickwts$feed = factor(chickwts$feed) ``` -------------------------------- ### Visualize ToothGrowth Data Source: https://richarddmorey.github.io/BayesFactor Generate a coplot to visualize the relationship between tooth length, dose, and supplement type in the ToothGrowth dataset. This helps in understanding the data before performing ANOVA. ```r data(ToothGrowth) coplot(len ~ dose | supp, data = ToothGrowth, panel = panel.smooth, xlab = "ToothGrowth data: length vs dose, given type of supplement") ``` -------------------------------- ### Create Pairwise Bayes Factor Comparisons Source: https://richarddmorey.github.io/BayesFactor Obtain pairwise comparisons by dividing a Bayes factor object by itself or a subset of itself. This results in a matrix of Bayes factor comparisons. ```R bfmat = allbf / allbf ``` -------------------------------- ### Recompute and Plot Posterior Chains Source: https://richarddmorey.github.io/BayesFactor Increase the number of iterations for posterior sampling and visualize the results. ```R chains2 = recompute(chains, iterations = 10000) plot(chains2[,1:2]) ``` -------------------------------- ### Estimate Posterior Parameters Source: https://richarddmorey.github.io/BayesFactor Uses MCMC methods to sample from the posterior of a model and summarizes the results. ```R ## Sample from the posterior of the full model chains = posterior(bfInteraction, iterations = 10000) ## 1:13 are the only "interesting" parameters summary(chains[,1:13]) ``` -------------------------------- ### Plotting Bayes Factors for ANOVA Models Source: https://richarddmorey.github.io/BayesFactor Visualizes the Bayes factors for different ANOVA models to show the magnitude of differences between them. This helps in understanding the relative evidence for each model. ```R plot(allBFs) ``` -------------------------------- ### Sample MCMC chains with column filtering Source: https://richarddmorey.github.io/BayesFactor Samples from the posterior of a linear model while excluding specific columns from the output using a regular expression. ```R chains = lmBF(RT ~ shape + color + shape:color + ID, data = puzzles, posterior = TRUE, iterations=10000,columnFilter="ID") ``` -------------------------------- ### Plotting Bayes Factor Comparisons Source: https://richarddmorey.github.io/BayesFactor Visualizes comparisons between specified models by dividing their Bayes factors. This helps in understanding the relative support for different models. ```r plot(bf[3:4] / bf[2]) ``` -------------------------------- ### Load Puzzles Dataset Source: https://richarddmorey.github.io/BayesFactor Loads the built-in puzzles dataset for mixed-model analysis. ```R data(puzzles) ``` -------------------------------- ### Plot Model Comparisons Source: https://richarddmorey.github.io/BayesFactor Visualize the relative Bayes factors of the top models using the `plot` function. ```R plot(bf2) ``` -------------------------------- ### Compare Models Using Bayes Factor Source: https://richarddmorey.github.io/BayesFactor Directly compute the Bayes factor between two models (e.g., full model vs. no-interaction model) to assess evidence for one over the other. ```R full / noInteraction ``` -------------------------------- ### Thin MCMC chains to reduce autocorrelation Source: https://richarddmorey.github.io/BayesFactor Recomputes an existing MCMC chain with thinning to obtain nearly independent samples, followed by checking the resulting dimensions. ```R chainsThinned = recompute(chains, iterations=20000, thin=2) # check size of MCMC chain dim(chainsThinned) ``` -------------------------------- ### Sampling from Posterior Distribution Source: https://richarddmorey.github.io/BayesFactor Sample from the posterior distribution of a specific model using the posterior function. Useful for detailed analysis of model parameters. ```R chains = posterior(complaintsLearningBf, iterations = 10000) summary(chains) ``` -------------------------------- ### Top-Down Bayes Factor Analysis with whichModels='top' Source: https://richarddmorey.github.io/BayesFactor Performs a top-down Bayes factor analysis, comparing the full model against models where single effects or interactions are omitted. This reduces the number of comparisons compared to testing all models. ```r bf = anovaBF(len ~ supp*dose, data=ToothGrowth, whichModels="top") bf ``` -------------------------------- ### Select a Specific Model for Comparison Source: https://richarddmorey.github.io/BayesFactor Access a specific model comparison from the Bayes factor object `bf` by its formula string. ```R bf["privileges + learning + raises + critical + advance"] ``` -------------------------------- ### Drawing Posterior Samples Source: https://richarddmorey.github.io/BayesFactor Draws samples from the posterior distribution of the true log odds and true probability using the 'posterior' function. Requires a Bayes factor object as input. ```R chains = posterior(bf, iterations = 10000) ``` -------------------------------- ### Define t-statistics and Sample Sizes for Meta-analysis Source: https://richarddmorey.github.io/BayesFactor Prepare vectors of t-statistics and corresponding sample sizes (n1 for one-sample t-tests, n1 and n2 for two-sample t-tests) for meta-analytic t-tests. ```r t = c(-.15, 2.39, 2.42, 2.43) N = c(100, 150, 97, 99) ``` -------------------------------- ### Sample Posterior Distribution for t-test Bayes Factor Source: https://richarddmorey.github.io/BayesFactor After computing a Bayes factor (bf), you can sample from the posterior distribution of the model parameters using the posterior function. This is useful for further analysis and visualization. ```r chains = posterior(bf, iterations = 10000) plot(chains[,2]) ``` -------------------------------- ### Classical Regression Analysis Summary Source: https://richarddmorey.github.io/BayesFactor Compare Bayesian results with classical linear model summaries. Note the difference in intercept interpretation due to Bayesian centering. ```R summary(lm(rating ~ complaints + learning, data = attitude)) ``` -------------------------------- ### Plot Bayes factor object Source: https://richarddmorey.github.io/BayesFactor Visualize model comparisons graphically. ```R plot(bf) ``` -------------------------------- ### Plotting Posterior Distribution of Rho Source: https://richarddmorey.github.io/BayesFactor Plots the full posterior distribution for the 'rho' parameter. Requires prior samples to be generated. ```R plot(samples[,"rho"]) ``` -------------------------------- ### Classical Analysis for Mixed Covariates Source: https://richarddmorey.github.io/BayesFactor Summary of a classical linear model including continuous (dose) and categorical (supp) covariates, and their interaction. ```R ## ## Call: ## lm(formula = len ~ supp + dose + supp:dose, data = ToothGrowth) ## ## Residuals: ## Min 1Q Median 3Q Max ## -7.543 -2.492 -0.503 2.712 7.857 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 20.663 0.679 30.43 < 2e-16 *** ## suppVC -3.700 0.960 -3.85 0.0003 *** ## dose 6.415 0.832 7.71 2.3e-10 *** ``` -------------------------------- ### Bayes Factor Analysis Output Source: https://richarddmorey.github.io/BayesFactor Interpreting the output of a Bayes factor analysis, showing the preference for one model over another. ```R ## Bayes factor analysis ## -------------- ## [1] complaints : 2.02 ±0.01% ## ## Against denominator: ## rating ~ complaints + learning ## --- ## Bayes factor type: BFlinearModel, JZS ``` -------------------------------- ### Default Bayes Factor Analysis with anovaBF Source: https://richarddmorey.github.io/BayesFactor Computes Bayes factors for all models against the intercept-only model using default settings. The `whichModels='withmain'` argument ensures interactions are only included if their constituent effects are also present. ```r bf = anovaBF(len ~ supp*dose, data=ToothGrowth) bf ``` -------------------------------- ### Perform multiple linear regression analysis Source: https://richarddmorey.github.io/BayesFactor Use standard R lm function to perform traditional multiple regression on the attitude dataset. ```R data(attitude) ## Traditional multiple regression analysis lmObj = lm(rating ~ ., data = attitude) summary(lmObj) ``` -------------------------------- ### Display Bayes factor object Source: https://richarddmorey.github.io/BayesFactor Inspect the contents of a Bayes factor object. ```R bf ``` -------------------------------- ### Plot MCMC estimate of probability difference Source: https://richarddmorey.github.io/BayesFactor Visualizes the MCMC estimate of the difference in probabilities. Useful for comparing conditional probabilities derived from posterior samples. ```R plot(mcmc(sameRaceGivenWhite - sameRaceGivenBlack), main = "Increase in probability of child picking\nsame race doll (white - black)") ``` -------------------------------- ### Classical Regression Summary Output Source: https://richarddmorey.github.io/BayesFactor Output from a classical linear regression analysis, providing estimates, standard errors, and significance for coefficients. ```R ## ## Call: ## lm(formula = rating ~ complaints + learning, data = attitude) ## ## Residuals: ## Min 1Q Median 3Q Max ## -11.56 -5.73 0.67 6.53 10.36 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 9.871 7.061 1.40 0.17 ## complaints 0.644 0.118 5.43 9.6e-06 *** ## learning 0.211 0.134 1.57 0.13 ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 6.82 on 27 degrees of freedom ## Multiple R-squared: 0.708, Adjusted R-squared: 0.686 ## F-statistic: 32.7 on 2 and 27 DF, p-value: 6.06e-08 ``` -------------------------------- ### Test random effects with lmBF Source: https://richarddmorey.github.io/BayesFactor Use lmBF to compare models when testing random effects directly. ```R bfWithoutID = lmBF(RT ~ shape*color, data = puzzles) bfWithoutID ``` ```R bfOnlyID = lmBF(RT ~ ID, whichRandom="ID",data = puzzles) bf2 = bfWithoutID / bfOnlyID bf2 ``` -------------------------------- ### Comparing Specific Models with lmBF Source: https://richarddmorey.github.io/BayesFactor Uses `lmBF` to compute Bayes factors for specific models of interest, allowing direct comparison between them. This is useful when only a few models need to be evaluated. ```r bfMainEffects = lmBF(len ~ supp + dose, data = ToothGrowth) bfInteraction = lmBF(len ~ supp + dose + supp:dose, data = ToothGrowth) ## Compare the two models bf = bfInteraction / bfMainEffects bf ``` -------------------------------- ### Plot Data for Two-Sample T-test Source: https://richarddmorey.github.io/BayesFactor Visualize the data for a two-sample t-test using a boxplot to compare weights across different feed types. ```R plot(weight ~ feed, data = chickwts, main = "Chick weights") ``` -------------------------------- ### Using regex to refine neverExclude Source: https://richarddmorey.github.io/BayesFactor Apply regular expressions to the neverExclude argument to match specific terms precisely. The ^ID$ pattern ensures only the exact ID term is protected, allowing interactions like shape:ID to be excluded. ```R puzzleGenBF <- generalTestBF(RT ~ shape + color + shape:color + shape:ID + ID, data=puzzles, whichRandom="ID", neverExclude="^ID$") puzzleGenBF ``` -------------------------------- ### Concatenate and compare Bayes factor objects Source: https://richarddmorey.github.io/BayesFactor Combine Bayes factor objects with the same denominator and perform division for comparison. ```R bfall = c(bf,bf2) ``` ```R bf[4] / bf2 ``` -------------------------------- ### Compute Meta-analytic Bayes Factor Source: https://richarddmorey.github.io/BayesFactor Use meta.ttestBF to compute a meta-analytic Bayes factor. Provide vectors of t-statistics and sample sizes. Optional arguments like nullInterval and rscale allow customization of the analysis. ```r bf = meta.ttestBF(t=t, n1=N, nullInterval=c(0,Inf), rscale=1) bf ``` -------------------------------- ### Find the Index of the Best Model Source: https://richarddmorey.github.io/BayesFactor The `which.max` function returns the index of the model with the highest Bayes factor. ```R which.max(bf) ``` -------------------------------- ### Plot Bayes Factor Object Source: https://richarddmorey.github.io/BayesFactor Generate a graphical representation of Bayes factors within a Bayes factor object. This helps visualize the relative evidence for different hypotheses. ```R plot(allbf) ``` -------------------------------- ### Recomputing Bayes Factor with Increased Iterations Source: https://richarddmorey.github.io/BayesFactor Increases the number of Monte Carlo samples used for integration to reduce the proportional error of the Bayes factor estimate. Use the `recompute` function with the `iterations` argument. ```r newbf = recompute(bf, iterations = 500000) newbf ``` -------------------------------- ### Perform Bayesian One-Sample T-Test Source: https://richarddmorey.github.io/BayesFactor Execute a Bayesian t-test using the ttestBF function, which assumes a Cauchy prior under the alternative hypothesis. ```R bf = ttestBF(x = diffScores) ## Equivalently: ## bf = ttestBF(x = sleep$extra[1:10],y=sleep$extra[11:20], paired=TRUE) bf ``` -------------------------------- ### Test Directional Hypotheses Source: https://richarddmorey.github.io/BayesFactor Use the nullInterval argument to test directional hypotheses against a point null. ```R bfInterval = ttestBF(x = diffScores, nullInterval=c(-Inf,0)) bfInterval ``` -------------------------------- ### Top-Down Bayes Factor Analysis Source: https://richarddmorey.github.io/BayesFactor Use `whichModels = "top"` in `regressionBF` to compare the most complex model against models where a single covariate is omitted. ```R bf = regressionBF(rating ~ ., data = attitude, whichModels = "top") ``` -------------------------------- ### Filter Models Based on Name Patterns Source: https://richarddmorey.github.io/BayesFactor Filters a set of BayesFactor models to exclude those containing both 'shape' and 'color' in their names. Uses `grepl` for pattern matching on model names. ```R # get the names of the numerator models missingModels = names(missing)$numerator # search them to see if they contain "shape" or "color" - # results are logical vectors containsShape = grepl("shape",missingModels) containsColor = grepl("color",missingModels) # anything that does not contain "shape" and "color" containsOnlyOne = !(containsShape & containsColor) # restrict missing to only those of interest missingOfInterest = missing[containsOnlyOne] missingOfInterest ``` -------------------------------- ### Disabling sampling for faster model culling Source: https://richarddmorey.github.io/BayesFactor Set noSample=TRUE in generalTestBF to prevent time-consuming sampling for complex models. Models requiring sampling will return NA. ```R puzzleCullBF <- generalTestBF(RT ~ shape + color + shape:color + ID, data=puzzles, whichRandom="ID", noSample=TRUE,whichModels='all') puzzleCullBF ``` -------------------------------- ### Compute Bayes Factors for All Additive Models Source: https://richarddmorey.github.io/BayesFactor Use `regressionBF` to compute Bayes factors for all possible additive models. The `.` in the formula represents all remaining columns besides 'rating'. ```R bf = regressionBF(rating ~ ., data = attitude) ``` -------------------------------- ### Recompute Missing Bayes Factors Source: https://richarddmorey.github.io/BayesFactor Computes the Bayes factors for a selected subset of models that were previously identified as missing. Uses the `recompute` function. ```R # recompute the Bayes factors for the missing models of interest sampledBayesFactors = recompute(missingOfInterest) sampledBayesFactors ``` -------------------------------- ### Sample Posterior Distribution of Correlation Source: https://richarddmorey.github.io/BayesFactor Samples from the posterior distribution of the correlation coefficient (rho) using the posterior function with a specified number of iterations. This is useful for estimating the correlation when it is assumed to be non-zero. ```R samples = posterior(bf, iterations = 10000) ``` -------------------------------- ### Calculate conditional probabilities from posterior chains Source: https://richarddmorey.github.io/BayesFactor Computes conditional probabilities (e.g., same race given child's race) from posterior MCMC chains. Assumes independent multinomial sampling plan. ```R sameRaceGivenWhite = chains[,"pi[1,1]"] / chains[,"pi[*,1]"] sameRaceGivenBlack = chains[,"pi[1,2]"] / chains[,"pi[*,2]"] ``` -------------------------------- ### Bayes Factor for Single Proportion Test Source: https://richarddmorey.github.io/BayesFactor Calculates the Bayes factor for a single proportion test. The null hypothesis assumes a fixed proportion p, while the alternative assumes a logistic distribution for the log-odds of p. The default prior scale 'r' is 0.5. ```R bf = proportionBF( 682, 682 + 243, p = 3/4) 1 / bf ``` -------------------------------- ### Compute Bayes Factor for Two-Sample Test Source: https://richarddmorey.github.io/BayesFactor Compute the Bayes factor for a two-sample test using the `ttestBF` function with the formula interface. This quantifies the evidence for the alternative hypothesis against the null hypothesis. ```R ttestBF(weight ~ feed, data = chickwts, var.eq=TRUE) ``` -------------------------------- ### Convert Bayes Factor Matrix to Matrix Source: https://richarddmorey.github.io/BayesFactor Convert a Bayes factor object to a standard matrix format using the `as.matrix` function. This is useful for further matrix operations or reporting. ```R as.matrix(bfmat) ``` -------------------------------- ### Compute Difference Scores and Traditional T-Test Source: https://richarddmorey.github.io/BayesFactor Calculate difference scores from the sleep dataset and perform a standard two-tailed t-test. ```R data(sleep) ## Compute difference scores diffScores = sleep$extra[1:10] - sleep$extra[11:20] ## Traditional two-tailed t test t.test(diffScores) ``` -------------------------------- ### Compute ANOVA with random effects Source: https://richarddmorey.github.io/BayesFactor Use anovaBF to specify random factors via the whichRandom argument. ```R bf = anovaBF(RT ~ shape*color + ID, data = puzzles, whichRandom="ID") ``` -------------------------------- ### Exact Binomial Test Source: https://richarddmorey.github.io/BayesFactor Performs an exact binomial test for comparison with the Bayes factor analysis. This function is part of base R. ```R binom.test(682, 682 + 243, p = 3/4) ``` -------------------------------- ### Compare Directional Hypotheses Source: https://richarddmorey.github.io/BayesFactor Divide Bayes factors from an interval test to compare two alternative hypotheses directly. ```R bfInterval[1] / bfInterval[2] ``` -------------------------------- ### Plotting Posterior of True Probability Source: https://richarddmorey.github.io/BayesFactor Plots the posterior distribution of the true probability of 'giant' progeny. This is generated after drawing posterior samples. ```R plot(chains[,"p"], main = "Posterior of true probability\nof 'giant' progeny") ``` -------------------------------- ### Combine Computed Bayes Factors Source: https://richarddmorey.github.io/BayesFactor Combines Bayes factors that were computed directly with those that were recomputed after sampling. Uses the `c` function for concatenation. ```R # Add them together with our other Bayes factors, already computed: completeBayesFactors = c(done, sampledBayesFactors) completeBayesFactors ``` -------------------------------- ### Filter MCMC Chain Output with lmBF Source: https://richarddmorey.github.io/BayesFactor Use the columnFilter argument in lmBF to exclude specific parameters from the MCMC output, thereby reducing memory usage. This suppresses output for columns matching the filter term but does not prevent estimation. ```R fullModelFiltered = lmBF(RT ~ shape + color + shape:color + ID, data = puzzles, noSample=TRUE, posterior = TRUE, iterations=3,columnFilter="ID") ``` ```R fullModelFiltered ``` -------------------------------- ### General test for linear models with fixed terms Source: https://richarddmorey.github.io/BayesFactor Tests hypotheses in linear models while ensuring specific terms are always included. Use 'neverExclude' to prevent nuisance parameters from being removed. ```R puzzleGenBF <- generalTestBF(RT ~ shape + color + shape:color + ID, data=puzzles, whichRandom="ID", neverExclude="ID") puzzleGenBF ``` -------------------------------- ### Perform Traditional Two-Sample T-test Source: https://richarddmorey.github.io/BayesFactor Conduct a traditional two-sample t-test to compare the means of two groups, assuming equal variances. ```R t.test(weight ~ feed, data = chickwts, var.eq=TRUE) ``` -------------------------------- ### Perform Within-Subjects ANOVA Source: https://richarddmorey.github.io/BayesFactor Conducts a traditional within-subjects ANOVA on the puzzles dataset. ```R summary(aov(RT ~ shape*color + Error(ID/(shape*color)), data=puzzles)) ``` -------------------------------- ### Combine Bayes Factors with Common Denominator Source: https://richarddmorey.github.io/BayesFactor Concatenate multiple Bayes factors that share the same denominator using the `c` function. This is useful when comparing different alternative hypotheses against the same null hypothesis. ```R allbf = c(bf, bfInterval) ``` -------------------------------- ### Manipulate Bayes Factor Objects Source: https://richarddmorey.github.io/BayesFactor Perform operations on Bayes factor objects, such as calculating the reciprocal or sampling from the posterior distribution. ```R 1 / bf ``` ```R chains = posterior(bf, iterations = 1000) summary(chains) ``` -------------------------------- ### Set custom prior scales per effect Source: https://richarddmorey.github.io/BayesFactor Configures specific prior scales for model effects using the rscaleEffects argument in anovaBF, overriding default fixed or random scales. ```R newprior.bf = anovaBF(RT ~ shape + color + shape:color + ID, data = puzzles, whichRandom = "ID",rscaleEffects = c( color = 1 )) newprior.bf ``` -------------------------------- ### General test for linear models Source: https://richarddmorey.github.io/BayesFactor Tests hypotheses about linear models by comparing a full model against successively reduced submodels. Handles categorical and continuous covariates. ```R data(puzzles) puzzleGenBF <- generalTestBF(RT ~ shape + color + shape:color + ID, data=puzzles, whichRandom="ID") puzzleGenBF ``` -------------------------------- ### Scatterplot and Linear Model for Iris Data Source: https://richarddmorey.github.io/BayesFactor Generates a scatterplot of Sepal.Width vs. Sepal.Length from the iris dataset and overlays a red line representing the linear regression model. This visually assesses the linear correlation between the two variables. ```R plot(Sepal.Width ~ Sepal.Length, data = iris) abline(lm(Sepal.Width ~ Sepal.Length, data = iris), col = "red") ``` -------------------------------- ### Subset Bayes Factor Matrix Source: https://richarddmorey.github.io/BayesFactor Extract individual Bayes factor objects or new lists from a Bayes factor matrix. This allows for focused analysis of specific comparisons. ```R bfmat[,2] ``` ```R bfmat[1,] ``` ```R bfmat[,1:2] ``` -------------------------------- ### Contingency Table Bayes Factor Source: https://richarddmorey.github.io/BayesFactor Computes the Bayes factor for contingency tables using the 'contingencyTableBF' function. Requires a matrix of cell frequencies and sampling plan details. ```R bf = contingencyTableBF(raceDolls, sampleType = "indepMulti", fixedMargin = "cols") bf ``` -------------------------------- ### Transpose Bayes Factor Matrix Source: https://richarddmorey.github.io/BayesFactor Transpose a Bayes factor matrix to change the orientation of numerators and denominators. This can be useful for different analytical perspectives. ```R t(bfmat[,1:2]) ``` -------------------------------- ### Chi-squared test for contingency tables Source: https://richarddmorey.github.io/BayesFactor Performs a chi-squared test with continuity correction on contingency table data. Use this for a classical statistical comparison. ```R chisq.test(raceDolls) ``` -------------------------------- ### Bayes Factor Test for Linear Correlation Source: https://richarddmorey.github.io/BayesFactor Computes the Bayes factor for the linear correlation between Sepal.Width and Sepal.Length in the iris dataset using the correlationBF function. The default prior scale is used. ```R bf = correlationBF(y = iris$Sepal.Length, x = iris$Sepal.Width)f ``` -------------------------------- ### Compute Bayes Factors for Linear Models Source: https://richarddmorey.github.io/BayesFactor Use lmBF to compute Bayes factors for various linear models against a null (intercept-only) model. Concatenate results into a single Bayes factor object for comparison. ```R full <- lmBF(len ~ supp + dose + supp:dose, data=ToothGrowth) noInteraction <- lmBF(len ~ supp + dose, data=ToothGrowth) onlyDose <- lmBF(len ~ dose, data=ToothGrowth) onlySupp <- lmBF(len ~ supp, data=ToothGrowth) allBFs <- c(full, noInteraction, onlyDose, onlySupp) allBFs ``` -------------------------------- ### Separate Missing and Done Bayes Factors Source: https://richarddmorey.github.io/BayesFactor Separates BayesFactor objects into those with computable values and those requiring sampling. Uses the `is.na` method for BayesFactor objects. ```R missing = puzzleCullBF[ is.na(puzzleCullBF) ] done = puzzleCullBF[ !is.na(puzzleCullBF) ] missing ``` -------------------------------- ### Classical Correlation Test for Iris Data Source: https://richarddmorey.github.io/BayesFactor Performs a classical Pearson's product-moment correlation test on the Sepal.Width and Sepal.Length from the iris dataset. This provides a p-value and confidence interval for the correlation coefficient. ```R cor.test(y = iris$Sepal.Length, x = iris$Sepal.Width) ``` -------------------------------- ### Compute Bayes Factor for t-test Source: https://richarddmorey.github.io/BayesFactor Use ttestBF to compute the Bayes factor for a t-test. Specify the formula and the data frame. The output includes the Bayes factor value and details about the alternative and null hypotheses. ```r bf = ttestBF(formula = weight ~ feed, data = chickwts) bf ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.