### Fit Bayesian Linear Models Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Examples demonstrating how to fit a Bayesian linear model using bayes.lm with custom priors and comparing results with standard lm. ```R data(bears) bears = subset(bears, Obs.No==1) bears = bears[,-c(1,2,3,11,12)] bears = bears[ ,c(7, 1:6)] bears$Sex = bears$Sex - 1 log.bears = data.frame(log.Weight = log(bears$Weight), bears[,2:7]) b0 = rep(0, 7) V0 = diag(rep(1e6,7)) fit = bayes.lm(log(Weight)~Sex+Head.L+Head.W+Neck.G+Length+Chest.G, data = bears, prior = list(b0 = b0, V0 = V0)) summary(fit) print(fit) ## Dobson (1990) Page 9: Plant Weight Data: ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14) trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69) group <- gl(2, 10, 20, labels = c("Ctl","Trt")) weight <- c(ctl, trt) lm.D9 <- lm(weight ~ group) bayes.D9 <- bayes.lm(weight ~ group) summary(lm.D9) summary(bayes.D9) ``` -------------------------------- ### Custom Prior Function Example Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Illustrates how to define a custom prior function for a Bayesian analysis, specifically replicating Dianna's prior, and then using it with the `poisgcp` function. ```APIDOC ## Example 10.1 Dianna's prior ### Description This example demonstrates how to define and use a custom prior function for a Bayesian analysis. ### Usage ```R f = function(mu){ result = rep(0, length(mu)) result[mu >=0 & mu <=2] = mu[mu >=0 & mu <=2] result[mu >=2 & mu <=4] = 2 result[mu >=4 & mu <=8] = 4 - 0.5 * mu[mu >=4 & mu <=8] A = 2 + 4 + 4 result = result / A return(result) } results = poisgcp(y, mu = c(0, 10), mu.prior = f) ``` ### Details - The function `f` defines a specific prior distribution. - `poisgcp` is used with the custom prior `f`. ``` -------------------------------- ### Perform Bayesian inference with normdp Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Examples demonstrating how to use normdp with uniform and non-uniform discrete priors. ```R ## generate a sample of 20 observations from a N(-0.5,1) population x = rnorm(20,-0.5,1) ## find the posterior density with a uniform prior on mu normdp(x,1) ## find the posterior density with a non-uniform prior on mu mu = seq(-3,3,by=0.1) mu.prior = runif(length(mu)) mu.prior = sort(mu.prior/sum(mu.prior)) normdp(x,1,mu,mu.prior) ## Let mu have the discrete distribution with 5 possible ## values, 2, 2.5, 3, 3.5 and 4, and associated prior probability of ## 0.1, 0.2, 0.4, 0.2, 0.1 respectively. Find the posterior ## distribution after a drawing random sample of n = 5 observations ## from a N(mu,1) distribution y = [1.52, 0.02, 3.35, 3.49, 1.82] mu = seq(2,4,by=0.5) mu.prior = c(0.1,0.2,0.4,0.2,0.1) y = c(1.52,0.02,3.35,3.49,1.82) normdp(y,1,mu,mu.prior) ``` -------------------------------- ### xdesign Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Simulates completely randomized design and randomized block designs. ```APIDOC ## Function: xdesign ### Description Monte Carlo study of randomized and blocked designs. Simulates completely randomized design and randomized block designs from a population of experimental units with underlying response values `yyy` and underlying other variable values `xxx` (possibly lurking). ### Usage ```R xdesign( x = NULL, y = NULL, corr = 0.8, size = 20, n.treatments = 4, n.rep = 500, ... ) ``` ### Arguments * `x` (numeric vector): A set of lurking values which are correlated with the response. * `y` (numeric vector): A set of response values. * `corr` (numeric): The correlation between the response and lurking variable. Defaults to 0.8. * `size` (integer): The size of the treatment groups. Defaults to 20. * `n.treatments` (integer): The number of treatments. Defaults to 4. * `n.rep` (integer): The number of Monte Carlo replicates. Defaults to 500. * `...`: Additional parameters which are passed to `Bolstad.control`. ### Value If the output of `xdesign` is assigned to a variable, then a list is returned with the following components: * `block.means` (vector): A vector of the means of the lurking variable from each replicate of the simulation stored by treatment number within replicate number. * `treat.means` (vector): A vector of the means of the response variable from each replicate of the simulation stored by treatment number within replicate number. * `ind` (vector): A vector containing the treatment group numbers. Note that there will be twice as many group numbers as there are treatments corresponding to the simulations done using a completely randomized design and the simulations done using a randomized block design. ### Examples ```R # Carry out simulations using the default parameters xdesign() # Carry out simulations using a simulated response with 5 treatments, # groups of size 25, and a correlation of -0.6 between the response # and lurking variable xdesign(corr = -0.6, size = 25, n.treatments = 5) ``` ``` -------------------------------- ### Generic Print Method for sintegral Objects Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html S3 print method for objects of class 'sintegral', designed to display the approximate value of the integral. ```R print(x, ...) ``` -------------------------------- ### Create prior default method Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Default method for creating a prior distribution with specified x values and weights. ```APIDOC ## Create prior default method ### Description Create prior default method ### Usage ```R ## Default S3 method: createPrior(x, wt, ...) ``` ### Arguments `x` | a vector of x values at which the prior is to be specified (the support of the prior). This should contain unique values in ascending order. The function will sort values if x is unsorted with a warning, and will halt if x contains any duplicates or negative lag 1 differences. `wt` | a vector of weights corresponding to the weight of the prior at the given x values. `...` | optional exta arguments. Not currently used. ``` -------------------------------- ### Analyze Bear Dataset Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Load the bears dataset and visualize weight distribution by sex. ```R data(bears) boxplot(Weight~Sex, data = bears) ``` -------------------------------- ### Simplest Binomial Mixture Prior Call Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Demonstrates the simplest usage of binomixp with 6 successes in 8 trials and a 50:50 mix of two uniform beta(1,1) priors. ```R binomixp(6,8) ``` -------------------------------- ### Print Method for Bolstad Objects Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Provides a print summary method for objects of class 'Bolstad', which are typically outputs from the `bayes.lm` function. It handles different class combinations for printing. ```APIDOC ## Print method for objects of class `Bolstad` ### Description This function provides a print summary method for the output of `bayes.lm`. ### Usage ```R ## S3 method for class 'Bolstad' print(x, digits = max(3L, getOption("digits") - 3L), ...) ``` ### Arguments - `x` (Bolstad): An object of class `Bolstad`. - `digits` (numeric): Number of digits to print. - `...`: Any other arguments to be passed to `print.default`. ### Details If `x` has both class `Bolstad` and `lm`, a print method similar to `print.lm` is called; otherwise, `print.default` is called. ### Author(s) James Curran ``` -------------------------------- ### Create Prior Default Method Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html The default S3 method for createPrior. It takes x values and corresponding weights to define the prior, ensuring the resulting function integrates to 1. ```R createPrior(x, wt, ...) ``` -------------------------------- ### Simulate Experimental Designs Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Simulates completely randomized and randomized block designs. Use default parameters for a quick simulation or customize correlation, group size, number of treatments, and replicates. ```R xdesign() ``` ```R xdesign(corr = -0.6, size = 25, n.treatments = 5) ``` -------------------------------- ### Print Method for sintegral Objects Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html A generic print method for objects of class 'sintegral', designed to display the approximate value of the integral. ```APIDOC ## Generic print method for sintegral objects ### Description Print the value of an `sintegral` object, specifically the (approximate) value of the integral. ### Usage ```R ## S3 method for class 'sintegral' print(x, ...) ``` ### Arguments - `x` (sintegral): An object of type `sintegral`. - `...`: Other parameters passed to `paste0`. ``` -------------------------------- ### Perform Bayesian inference with general conjugate priors using normgcp Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Demonstrates generating samples, calculating posterior densities with uniform and user-defined priors, and computing credible intervals using CDF and summary functions. ```R ## generate a sample of 20 observations from a N(-0.5,1) population x = rnorm(20,-0.5,1) ## find the posterior density with a uniform U[-3,3] prior on mu normgcp(x, 1, params = c(-3, 3)) ## find the posterior density with a non-uniform prior on mu mu = seq(-3, 3, by = 0.1) mu.prior = rep(0, length(mu)) mu.prior[mu <= 0] = 1 / 3 + mu[mu <= 0] /9 mu.prior[mu > 0] = 1 / 3 - mu[mu > 0] / 9 normgcp(x, 1, density = "user", mu = mu, mu.prior = mu.prior) ## find the CDF for the previous example and plot it ## Note the syntax for sintegral has changed results = normgcp(x,1,density="user",mu=mu,mu.prior=mu.prior) cdf = sintegral(mu,results$posterior,n.pts=length(mu))$cdf plot(cdf,type="l",xlab=expression(mu[0]) ,ylab=expression(Pr(mu<=mu[0]))) ## use the CDF for the previous example to find a 95% ## credible interval for mu. Thanks to John Wilkinson for this simplified code lcb = cdf$x[with(cdf,which.max(x[y<=0.025]))] ucb = cdf$x[with(cdf,which.max(x[y<=0.975]))] cat(paste("Approximate 95% credible interval : [" ,round(lcb,4)," ",round(ucb,4),"]\n",sep="")) ## use the CDF from the previous example to find the posterior mean ## and std. deviation dens = mu*results$posterior post.mean = sintegral(mu,dens)$value dens = (mu-post.mean)^2*results$posterior post.var = sintegral(mu,dens)$value post.sd = sqrt(post.var) ## use the mean and std. deviation from the previous example to find ## an approximate 95% credible interval lb = post.mean-qnorm(0.975)*post.sd ub = post.mean+qnorm(0.975)*post.sd cat(paste("Approximate 95% credible interval : [" ,round(lb,4)," ",round(ub,4),"]\n",sep="")) ## repeat the last example but use the new summary functions for the posterior results = normgcp(x, 1, density = "user", mu = mu, mu.prior = mu.prior) ## use the cdf function to get the cdf and plot it postCDF = cdf(results) ## note this is a function plot(results$mu, postCDF(results$mu), type="l", xlab = expression(mu[0]), ylab = expression(Pr(mu <= mu[0]))) ## use the quantile function to get a 95% credible interval ci = quantile(results, c(0.025, 0.975)) ci ## use the mean and sd functions to get the posterior mean and standard deviation postMean = mean(results) postSD = sd(results) postMean postSD ## use the mean and std. deviation from the previous example to find ## an approximate 95% credible interval ciApprox = postMean + c(-1,1) * qnorm(0.975) * postSD ciApprox ``` -------------------------------- ### Poisson Sampling with User-Specified Continuous Prior Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Performs Poisson sampling using a user-defined continuous prior distribution for the mean rate (mu). This allows for flexible prior specifications beyond standard parametric forms. It also demonstrates how to obtain a 99% credible interval using the alpha parameter. ```R y = c(3,4,3,0,1) mu = seq(0,8,by=0.001) mu.prior = c(seq(0,2,by=0.001),rep(2,1999),seq(2,0,by=-0.0005))/10 poisgcp(y,"user",mu=mu,mu.prior=mu.prior,print.sum.stat=TRUE,alpha=0.01) ``` -------------------------------- ### Load and Plot Sample Data Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Loads the sscsample.data dataset and creates a scatter plot of income versus ethnicity. Ensure the data is loaded before plotting. ```R data(sscsample.data) plot(income~ethnicity, data = sscsample.data) ``` -------------------------------- ### Print Method for Bolstad Objects Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html S3 print method for objects of class 'Bolstad', providing a summary similar to 'print.lm' if the object also has class 'lm', otherwise using 'print.default'. ```R print(x, digits = max(3L, getOption("digits") - 3L), ...) ``` -------------------------------- ### Binomial Mixture Prior with Multiple Non-Uniform Priors and Plotting Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Performs binomial sampling with 4 successes in 12 trials, using a 90:10 mix of non-uniform beta(3,3) and beta(4,12) priors. It also plots the prior, likelihood, and posterior densities. ```R results = binomixp(4, 12, c(3, 3), c(4, 12), 0.9)$mix par(mfrow = c(3,1)) y.lims = c(0, 1.1 * max(results$posterior, results$prior)) plot(results$pi,results$prior,ylim=y.lims,type='l' ,xlab=expression(pi),ylab='Density',main='Prior') polygon(results$pi,results$prior,col='red') plot(results$pi,results$likelihood,type='l', xlab = expression(pi), ylab = 'Density', main = 'Likelihood') polygon(results$pi,results$likelihood,col='green') plot(results$pi,results$posterior,ylim=y.lims,type='l' ,xlab=expression(pi),ylab='Density',main='Posterior') polygon(results$pi,results$posterior,col='blue') ``` -------------------------------- ### Perform Bayesian inference with mixture of normal priors using normmixp Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Demonstrates generating samples and calculating posterior densities using different normal prior mixtures. ```R ## generate a sample of 20 observations from a N(-0.5, 1) population x = rnorm(20, -0.5, 1) ## find the posterior density with a N(0, 1) prior on mu - a 50:50 mix of ## two N(0, 1) densities normmixp(x, 1, c(0, 1), c(0, 1)) ## find the posterior density with 50:50 mix of a N(0.5, 3) prior and a ## N(0, 1) prior on mu normmixp(x, 1, c(0.5, 3), c(0, 1)) ## Find the posterior density for mu, given a random sample of 4 ## observations from N(mu, 1), y = [2.99, 5.56, 2.83, 3.47], ``` -------------------------------- ### Posterior Quantiles Method for Bolstad Objects Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html S3 quantile method for objects of class 'Bolstad'. It calculates posterior quantiles using numerical integration and linear interpolation. ```R quantile(x, probs = seq(0, 1, 0.25), ...) ``` -------------------------------- ### Binomial Sampling with Continuous Prior Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Evaluates posterior density for binomial success probability with a general continuous prior. Supports various prior distributions like beta, exponential, normal, or user-defined. ```R binogcp(6, 8) ``` ```R binogcp(6, 8,density = "beta", params = c(2, 2)) ``` ```R binogcp(5, 10, density = "normal", params = c(0.5, 0.25)) ``` ```R pi = seq(0, 1,by = 0.001) pi.prior = rep(0, length(pi)) priorFun = createPrior(x = c(0, 0.5, 1), wt = c(0, 2, 0)) pi.prior = priorFun(pi) results = binogcp(4, 12, "user", pi = pi, pi.prior = pi.prior) ``` ```R myCdf = cdf(results) plot(myCdf, type = "l", xlab = expression(pi[0]), ylab = expression(Pr(pi <= pi[0]))) ``` ```R qtls = quantile(results, probs = c(0.025, 0.975)) cat(paste("Approximate 95% credible interval : [" , round(qtls[1], 4), " ", round(qtls, 4), "]\n", sep = "")) ``` ```R post.mean = mean(results) post.var = var(results) post.sd = sd(results) ``` ```R # calculate an approximate 95% credible region using the posterior mean and ``` -------------------------------- ### Posterior CDF and Credible Region Calculation Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Demonstrates how to calculate the posterior Cumulative Distribution Function (CDF) and find credible intervals using the results from a Bayesian analysis. It also shows how to calculate the posterior mean, variance, and standard deviation. ```APIDOC ## Posterior CDF and Credible Region Calculation This section shows how to compute the posterior CDF and credible regions from a Bayesian analysis. ### Usage ```R results = poisgcp(y,"user",mu=mu,mu.prior=mu.prior) cdf = cdf(results) curve(cdf,type="l",xlab=expression(mu[0]), ylab=expression(Pr(mu<=mu[0]))) ci = quantile(results, c(0.025, 0.975)) cat(paste0("Approximate 95% credible interval : [", round(ci[1],4)," ",round(ci[2],4),"]\n")) post.mean = mean(results) post.var = var(results) post.sd = sd(results) ci = post.mean + c(-1, 1) * qnorm(0.975) * post.sd cat(paste("Approximate 95% credible interval : [" , round(ci[1],4)," ",round(ci[2],4),"]\n",sep="")) ``` ### Details - `poisgcp`: Function to perform Poisson generalized conjugate prior analysis. - `cdf`: Extracts the cumulative distribution function from the results. - `curve`: Plots the CDF. - `quantile`: Calculates quantiles of the posterior distribution. - `mean`, `var`, `sd`: Calculate posterior mean, variance, and standard deviation. ``` -------------------------------- ### Perform Bayesian Linear Regression with bayes.lin.reg Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Demonstrates fitting linear models with various prior configurations and generating predictions. ```R ## generate some data from a known model, where the true value of the ## intercept alpha is 2, the true value of the slope beta is 3, and the ## errors come from a normal(0,1) distribution set.seed(123) x = rnorm(50) y = 2 + 3*x + rnorm(50) ## use the function with a flat prior for the slope beta and a ## flat prior for the intercept, alpha_xbar. bayes.lin.reg(y,x) ## use the function with a normal(0,3) prior for the slope beta and a ## normal(30,10) prior for the intercept, alpha_xbar. bayes.lin.reg(y,x,"n","n",0,3,30,10) ## use the same data but plot it and the credible interval bayes.lin.reg(y,x,"n","n",0,3,30,10, plot.data = TRUE) ## The heart rate vs. O2 uptake example 14.1 O2 = c(0.47,0.75,0.83,0.98,1.18,1.29,1.40,1.60,1.75,1.90,2.23) HR = c(94,96,94,95,104,106,108,113,115,121,131) plot(HR,O2,xlab="Heart Rate",ylab="Oxygen uptake (Percent)") bayes.lin.reg(O2,HR,"n","f",0,1,sigma=0.13) ## Repeat the example but obtain predictions for HR = 100 and 110 bayes.lin.reg(O2,HR,"n","f",0,1,sigma=0.13,pred.x=c(100,110)) ``` -------------------------------- ### Poisson sampling with a discrete prior Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Evaluates and plots the posterior density for the mean rate of a Poisson process using a discrete prior. ```R ## simplest call with an observation of 4 and a uniform prior on the ## values mu = 1,2,3 poisdp(4,1:3,c(1,1,1)/3) ## Same as the previous example but a non-uniform discrete prior mu = 1:3 mu.prior = c(0.3,0.4,0.3) poisdp(4,mu=mu,mu.prior=mu.prior) ## Same as the previous example but a non-uniform discrete prior mu = seq(0.5,9.5,by=0.05) mu.prior = runif(length(mu)) mu.prior = sort(mu.prior/sum(mu.prior)) poisdp(4,mu=mu,mu.prior=mu.prior) ## A random sample of 50 observations from a Poisson distribution with ## parameter mu = 3 and non-uniform prior y.obs = rpois(50,3) mu = c(1:5) mu.prior = c(0.1,0.1,0.05,0.25,0.5) results = poisdp(y.obs, mu, mu.prior) ## Same as the previous example but a non-uniform discrete prior mu = seq(0.5,5.5,by=0.05) mu.prior = runif(length(mu)) mu.prior = sort(mu.prior/sum(mu.prior)) y.obs = rpois(50,3) poisdp(y.obs,mu=mu,mu.prior=mu.prior) ``` -------------------------------- ### Plot Prior, Likelihood, and Posterior Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Plots the prior, likelihood, and posterior distributions on a single graph to visualize their influence. Ensure the input is an object of class 'Bolstad'. ```R decomp(x, ...) ``` ```R # an example with a binomial sampling situation results = binobp(4, 12, 3, 3, plot = FALSE) decomp(results) ``` ```R # an example with normal data y = c(2.99,5.56,2.83,3.47) results = normnp(y, 3, 2, 1, plot = FALSE) decomp(results) ``` -------------------------------- ### Calculate Posterior CDF and Quantiles Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Finds the posterior CDF and calculates the 95% credible interval using the quantile function on the results from a poisgcp model. ```R results = poisgcp(y,"user",mu=mu,mu.prior=mu.prior) cdf = cdf(results) curve(cdf,type="l",xlab=expression(mu[0]) ,ylab=expression(Pr(mu<=mu[0]))) ci = quantile(results, c(0.025, 0.975)) cat(paste0("Approximate 95% credible interval : [" ,round(ci[1],4)," ",round(ci[2],4),"]\n")) ``` -------------------------------- ### Binomial Sampling with Discrete Prior Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Evaluate posterior density for binomial sampling using a discrete prior. ```R binodp(x, n, pi = NULL, pi.prior = NULL, n.pi = 10, ...) ``` -------------------------------- ### Binomial Mixture Prior with Non-Uniform Priors Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Shows binomixp with 6 successes in 8 trials, using a 20:80 mix of a non-uniform beta(0.5,6) prior and a uniform beta(1,1) prior. ```R binomixp(6,8,alpha0=c(0.5,6),alpha1=c(1,1),p=0.2) ``` -------------------------------- ### Calculate Credible Interval for Poisson Mean with Gamma Prior (Quantile Method) Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Calculates a 95% credible interval for the mean (mu) of a Poisson distribution using a gamma prior. This method uses the quantile function on the results of poisgamp to determine the interval bounds. ```R y = c(3,4,4,3,3,4,2,3,1,7) results = poisgamp(y, 6, 3) ci = quantile(results, c(0.025, 0.975)) cat(paste("95% credible interval for mu: [",round(ci[1],3), "," ,round(ci[2],3)),"] ) ``` -------------------------------- ### Binomial sampling with a beta mixture prior Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Evaluates and plots the posterior density for π, the probability of a success in a Bernoulli trial, with binomial sampling when the prior density for π is a mixture of two beta distributions. ```APIDOC ## Binomial sampling with a beta mixture prior ### Description Evaluates and plots the posterior density for `πππ`, the probability of a success in a Bernoulli trial, with binomial sampling when the prior density for `πππ` is a mixture of two beta distributions, `beta(a0,b0)beta(a_0,b_0)beta(a0​,b0​)` and `beta(a1,b1)beta(a_1,b_1)beta(a1​,b1​)`. ### Usage ```R binomixp(x, n, alpha0 = c(1, 1), alpha1 = c(1, 1), p = 0.5, ...) ``` ### Arguments `x` | the number of observed successes in the binomial experiment. `n` | the number of trials in the binomial experiment. `alpha0` | a vector of length two containing the parameters, `a0a_0a0​` and `b0b_0b0​`, for the first component beta prior - must be greater than zero. By default the elements of alpha0 are set to 1. `alpha1` | a vector of length two containing the parameters, `a1a_1a1​` and `b1b_1b1​`, for the second component beta prior - must be greater than zero. By default the elements of alpha1 are set to 1. `p` | The prior mixing proportion for the two component beta priors. That is the prior is `pimesbeta(a0,b0)+(1−p)imesbeta(a1,b1)pimes beta(a_0,b_0)+(1-p)imes beta(a_1,b_1)pimesbeta(a0​,b0​)+(1−p)imesbeta(a1​,b1​)`. `...` | additional arguments that are passed to `Bolstad.control` ### Value A list will be returned with the following components: `pi` | the values of `πππ` for which the posterior density was evaluated `posterior` | the posterior density of `πππ` given `nnn` and `xxx` `likelihood` | the likelihood function for `πππ` given `xxx` and `nnn`, i.e. the `binomial(n,π)binomial(n,π)binomial(n,π)` density `prior` | the prior density of `πππ` density ### See Also `binodp` `binogcp` `normmixp` ### Examples ```R # simplest call with 6 successes observed in 8 trials and a 50:50 mix # of two beta(1,1) uniform priors binomixp(6,8) # 6 successes observed in 8 trials and a 20:80 mix of a non-uniform # beta(0.5,6) prior and a uniform beta(1,1) prior binomixp(6,8,alpha0=c(0.5,6),alpha1=c(1,1),p=0.2) # 4 successes observed in 12 trials with a 90:10 non uniform beta(3,3) prior # and a non uniform beta(4,12). # Plot the stored prior, likelihood and posterior results = binomixp(4, 12, c(3, 3), c(4, 12), 0.9)$mix par(mfrow = c(3,1)) y.lims = c(0, 1.1 * max(results$posterior, results$prior)) plot(results$pi,results$prior,ylim=y.lims,type='l' ,xlab=expression(pi),ylab='Density',main='Prior') polygon(results$pi,results$prior,col='red') plot(results$pi,results$likelihood,type='l', xlab = expression(pi), ylab = 'Density', main = 'Likelihood') polygon(results$pi,results$likelihood,col='green') plot(results$pi,results$posterior,ylim=y.lims,type='l' ,xlab=expression(pi),ylab='Density',main='Posterior') polygon(results$pi,results$posterior,col='blue') ``` ``` -------------------------------- ### Binomial Sampling with Beta Prior Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Evaluate posterior density for binomial sampling using a beta prior. ```R binobp(x, n, a = 1, b = 1, pi = seq(0, 1, by = 0.001), ...) ``` ```R binobp(6,8) ``` ```R binobp(6,8,0.5,6) ``` ```R results = binobp(4, 12, 3, 3) decomp(results) ``` -------------------------------- ### Poisson sampling with a gamma prior Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Evaluates and plots the posterior density for the mean rate of a Poisson process using a gamma prior. ```R ## simplest call with an observation of 4 and a gamma(1, 1), i.e. an exponential prior on the ## mu poisgamp(4, 1, 1) ## Same as the previous example but a gamma(10, ) prior poisgamp(4, 10, 1) ## Same as the previous example but an improper gamma(1, ) prior poisgamp(4, 1, 0) ## A random sample of 50 observations from a Poisson distribution with ## parameter mu = 3 and gamma(6,3) prior set.seed(123) y = rpois(50,3) poisgamp(y,6,3) ## In this example we have a random sample from a Poisson distribution ``` -------------------------------- ### Plotting Bolstad objects Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Visualizes prior, likelihood, and posterior distributions from a Bolstad object. ```R x = rnorm(20,-0.5,1) ## find the posterior density with a N(0,1) prior on mu b = normnp(x,sigma=1) plot(b) plot(b, which = 1:3) plot(b, overlay = FALSE, which = 1:3) ``` -------------------------------- ### binogcp Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Evaluates binomial sampling with a general continuous prior. ```APIDOC ## binogcp ### Description Evaluates and plots the posterior density for the probability of success in a Bernoulli trial with a continuous prior. ### Parameters #### Arguments - **x** (numeric) - Required - The number of observed successes. - **n** (numeric) - Required - The number of trials. - **density** (string) - Required - One of 'beta', 'exp', 'normal', 'student', 'uniform', or 'user'. - **params** (vector) - Optional - Parameters for the chosen density. - **n.pi** (numeric) - Optional - Number of possible pi values. - **pi** (vector) - Optional - Vector of possibilities for pi (required if density='user'). - **pi.prior** (vector) - Optional - Associated prior probability mass (required if density='user'). ### Response #### Success Response - **likelihood** (vector) - The scaled likelihood function. - **posterior** (vector) - The posterior probability. - **pi** (vector) - The vector of possible pi values. - **pi.prior** (vector) - The associated probability mass. ``` -------------------------------- ### Print Method for sscsample Objects Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Provides a print summary method for objects of class 'sscsamp', generated by the `sscsample` function. It displays sample means and stratum counts. ```APIDOC ## Print method for objects of class `sscsample` ### Description This function provides a print summary method for the output of `sscsample`. The `sscsample` produces a large number of samples from a fixed population using either simple random, stratified, or cluster sampling. This function provides the means of each sample plus the number of observations from each ethnicity stratum in the sample. ### Usage ```R ## S3 method for class 'sscsamp' print(x, ...) ``` ### Arguments - `x` (sscsamp): An object of class `sscsamp` produced by `sscsample`. - `...`: Any other arguments that are to be passed to `cat`. ### Author(s) James Curran ``` -------------------------------- ### POST /poisgamp Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Evaluates and plots the posterior density for the mean rate of occurrence in a Poisson process using a gamma prior. ```APIDOC ## POST /poisgamp ### Description Evaluates and plots the posterior density for μ, the mean rate of occurrence in a Poisson process and a gamma prior on μ. ### Method POST ### Endpoint /poisgamp ### Parameters #### Request Body - **y** (vector) - Required - A random sample from a Poisson distribution. - **shape** (numeric) - Required - The shape parameter of the gamma prior. - **rate** (numeric) - Optional - The rate parameter of the gamma prior. - **scale** (numeric) - Optional - The scale parameter of the gamma prior. - **alpha** (numeric) - Optional - The width of the credible interval. ### Response #### Success Response (200) - **prior** (vector) - The prior density assigned to μ. - **likelihood** (vector) - The scaled likelihood function for μ given y. - **posterior** (vector) - The posterior probability of μ given y. - **shape** (numeric) - The shape parameter for the gamma posterior. - **rate** (numeric) - The rate parameter for the gamma posterior. ``` -------------------------------- ### Posterior Quantiles for Bolstad Objects Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Calculates posterior quantiles for objects of class 'Bolstad'. This method uses numerical integration and linear interpolation if necessary. ```APIDOC ## Posterior quantiles for Bolstad objects ### Description Calculates posterior quantiles for objects of class 'Bolstad'. ### Usage ```R ## S3 method for class 'Bolstad' quantile(x, probs = seq(0, 1, 0.25), ...) ``` ### Arguments - `x` (Bolstad): An object of class `Bolstad`. - `probs` (numeric): Vector of probabilities in the range [0, 1]. - `...`: Any extra arguments needed. ### Details If `x` is of class `Bolstad`, this function finds the quantiles of the posterior distribution using numerical integration and linear interpolation. ``` -------------------------------- ### Summary Method for bayes.lm Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Provides a summary of a 'Bolstad' object, which is the output of the bayes.lm function. This method is used to inspect the results of a Bayesian linear model fit. ```R summary(object, ...) ``` -------------------------------- ### Create prior generic Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Creates a prior distribution function through linear interpolation. ```APIDOC ## Create prior generic ### Description Create prior generic ### Usage ```R createPrior(x, ...) ``` ### Arguments `x` | a vector of x values at which the prior is to be specified (the support of the prior). `...` | optional exta arguments. Not currently used. ### Value a linear interpolation function where the weights have been scaled so the function (numerically) integrates to 1. ``` -------------------------------- ### summary.Bolstad Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Provides a summary method for objects created by the bayes.lm function. ```APIDOC ## S3 Method: summary.Bolstad ### Description `summary` method for output of `bayes.lm`. ### Usage ```R ## S3 method for class 'Bolstad' summary(object, ...) ``` ### Arguments * `object` (Bolstad): An object of class 'Bolstad' that is the result of a call to `bayes.lm`. * `...`: Any further arguments to be passed to `print`. ### See Also * `bayes.lm`: The function to fit the model. * `coef`: Function to extract the matrix of posterior means along with standard errors and t-statistics. ``` -------------------------------- ### Binomial Probability with Discrete Prior Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Calculates binomial probabilities with a discrete prior. Use for scenarios with a fixed number of trials and successes, and a defined prior distribution for the success probability. ```R binodp(6,8) ``` ```R binodp(6, 8, n.pi = 100) ``` ```R pi = seq(0, 1, by = 0.01) pi.prior = runif(101) pi.prior = sort(pi.prior / sum(pi.prior)) binodp(6, 8, pi, pi.prior) ``` ```R pi = c(0.3, 0.4, 0.5) pi.prior = c(0.2, 0.3, 0.5) results = binodp(5, 6, pi, pi.prior) ``` ```R results.matrix = rbind(results$pi.prior,results$posterior) colnames(results.matrix) = pi barplot(results.matrix, col = c("red", "blue"), beside = TRUE, xlab = expression(pi), ylab=expression(Probability(pi))) box() legend("topleft", bty = "n", cex = 0.7, legend = c("Prior", "Posterior"), fill = c("red", "blue")) ``` -------------------------------- ### Plot Moisture Data Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Plots the final moisture level against the in-process moisture level using the 'moisture.df' dataset. ```R data(moisture.df) plot(final.level~proc.level, data = moisture.df) ``` -------------------------------- ### POST /poisdp Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Evaluates and plots the posterior density for the mean rate of occurrence in a Poisson process using a discrete prior. ```APIDOC ## POST /poisdp ### Description Evaluates and plots the posterior density for μ, the mean rate of occurrence in a Poisson process and a discrete prior on μ. ### Method POST ### Endpoint /poisdp ### Parameters #### Request Body - **y.obs** (vector) - Required - A random sample from a Poisson distribution. - **mu** (vector) - Required - A vector of possibilities for the mean rate of occurrence. - **mu.prior** (vector) - Required - The associated prior probability mass. ### Response #### Success Response (200) - **likelihood** (vector) - The scaled likelihood function for μ given y.obs. - **posterior** (vector) - The posterior probability of μ given y.obs. - **mu** (vector) - The vector of possible μ values used in the prior. - **mu.prior** (vector) - The associated probability mass for the values in μ. ``` -------------------------------- ### median(x, na.rm = FALSE, ...) Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Computes the posterior median of the posterior distribution. ```APIDOC ## median(x, na.rm = FALSE, ...) ### Description Compute the posterior median of the posterior distribution for a Bolstad object. ### Parameters #### Arguments - **x** (Bolstad object) - Required - An object of class Bolstad. - **na.rm** (boolean) - Optional - Ideally removes missing values (not currently used). - **...** (dots) - Optional - Not currently used. ``` -------------------------------- ### Create Prior Function Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html A generic function to create a prior distribution. It takes a vector of x values (support) and returns a linear interpolation function scaled to integrate to 1. ```R createPrior(x, ...) ``` -------------------------------- ### Poisson Sampling with Gamma Prior Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Performs Poisson sampling with a gamma prior distribution for the mean rate (mu). This is a common choice for a conjugate prior in Poisson models. ```R y = c(3,4,3,0,1) poisgcp(y, density = "gamma", params = c(6,8)) ``` -------------------------------- ### sscsample Source: https://cran.r-project.org/web/packages/Bolstad/refman/Bolstad.html Samples from a fixed population using either simple random sampling, stratified sampling or cluster sampling. ```APIDOC ## sscsample ### Description Samples from a fixed population using either simple random sampling, stratitified sampling or cluster sampling. ### Usage ```R sscsample( size, n.samples, sample.type = c("simple", "cluster", "stratified"), x = NULL, strata = NULL, cluster = NULL ) ``` ### Arguments `size` | the desired size of the sample `n.samples` | the number of repeat samples to take `sample.type` | the sampling method. Can be one of "simple", "stratified", "cluser" or 1, 2, 3 where 1 corresponds to "simple", 2 to "stratified" and 3 to "cluster" `x` | a vector of measurements for each unit in the population. By default x is not used, and the builtin data set sscsample.data is used `strata` | a corresponding vector for each unit in the population indicating membership to a stratum `cluster` | a corresponding vector for each unit in the population indicating membership to a cluster ### Value A list will be returned with the following components: `samples` | a matrix with the number of rows equal to size and the number of columns equal to n.samples. Each column corresponds to a sample drawn from the population `s.strata` | a matrix showing how many units from each stratum were included in the sample `means` | a vector containing the mean of each sample drawn ### Author(s) James M. Curran, Dept. of Statistics, University of Auckland. Janko Dietzsch, Proteomics Algorithm and Simulation,Zentrum f. Bioinformatik Tuebingen Fakultaet f. Informations- und Kognitionswissenschaften, Universitaet Tuebingen ### Examples ```R ## Draw 200 samples of size 20 using simple random sampling sscsample(20,200) ## Draw 200 samples of size 20 using simple random sampling and store the ## results. Extract the means of all 200 samples, and the 50th sample res = sscsample(20,200) res$means res$samples[,50] ``` ```