1 Bayes Theorem

In the context of Bayes’ Theorem:

  • Hypothesis (A): This is a statement or proposition that you want to assess or make predictions about. It’s what you’re trying to understand or evaluate. In medical contexts, this could be the presence or absence of a disease, and in general statistical analysis, it could be any statement about a population or process.

  • Evidence (B): This is new information or data that you have, which is relevant to the hypothesis. It’s something observed or measured. In medical testing, this could be the result of a diagnostic test, and in general statistical analysis, it could be any kind of observed data.

Bayes’ Theorem is a mathematical concept that calculates the probability of a hypothesis (A) based on prior knowledge or beliefs. It involves updating our initial beliefs with new evidence (B). The formula is:

\(P(A∣B)=\dfrac{P(B∣A)×P(A)}{P(B)}\)

where

  • \(P(A∣B)\) is the probability of hypothesis A given evidence B.

  • \(P(B∣A)\) is the probability of evidence B given hypothesis A.

  • \(P(A)\) is the prior probability of hypothesis A.

  • \(P(B)\) is the prior probability of evidence B.

Example: Suppose we want to know the probability of someone having a rare disease (A) given a positive test result (B). If we know the sensitivity of the test (probability of a positive result given the disease) is 0.95, the prevalence of the disease in the population is 0.01, and the specificity of the test (probability of a negative result given the absence of the disease) is 0.90, Bayes’ Theorem helps us calculate the updated probability.

Applying the formula, we find \(P(A|B)\) to assess the likelihood of the disease given the positive test result.

  • Bayes’ Theorem builds upon the principles of conditional probability.

  • The prior probability \(P(A)\), which is our initial belief in the absence of new evidence (before the evidence), gets updated based on the likelihood \(P(B|A)\) and the marginal probability of the evidence \(P(B)\).

    • The fraction \(\dfrac{P(B|A)}{P(B)}\) represents the "strength of the evidence". It compares how likely the evidence is under the hypothesis \(A\) to its overall likelihood, helping to weigh the impact of the evidence on the posterior probability.

      • Likelihood: \(P(B∣A)\) is the likelihood, representing the probability of observing the evidence \(B\) given that the hypothesis \(A\) is true. It gauges how well the hypothesis explains the observed evidence.

      • Marginal Probability: \(P(B)\) is the marginal probability of the evidence, which can be interpreted as the probability of observing the evidence \(B\) regardless of whether the hypothesis \(A\) is true or not. It serves as a normalization factor in Bayes’ Theorem.

  • This updating process results in the posterior probability \(P(A|B)\), reflecting our revised belief given the new evidence.

The formulation of Posterior = likelihood * prior / evidence captures the essence of Bayes’ Theorem. It’s a powerful tool for updating beliefs or probabilities based on new information.

2 Bayes Theorem Question

Bayes’ Theorem can yield surprising results. Take a look at Guided Practice 3.43 (Open Stats) and attempt to solve this using Bayes’ formula. Interpret the results. Then use the attached code and solve via a tree diagram in R. You will need to change the initial parameters to the appropriate values. Attach your final graph to your submission. Note: for newer versions of R, you will need to install BiocManagerand Rgraphviz-

install.packages("BiocManager")

library(BiocManager)

BiocManager::install("Rgraphviz")

Guided Practice 3.43: Jose visits campus every Thursday evening. However, some days the parking garage is full, often due to college events. There are academic events on 35% of evenings, sporting events on 20% of evenings, and no events on 45% of evenings. When there is an academic event, the garage fills up about 25% of the time, and it fills up 70% of evenings with sporting events. On evenings when there are no events, it only fills up about 5% of the time. \ If Jose comes to campus and finds the garage full, what is the probability that there is a sporting event? Use a tree diagram to solve this problem.

If Jose comes to campus and finds the garage full, the probability that there is a sporting event is 56%.

The R code for Bayesian probability can be written in a few lines too. See ``G. Jay Kerns, 2010, Introduction to Probability and Statistics Using R’’ for more details.

rm(list = ls())   # Clear environment 
gc()              # Clear unused memory
##          used (Mb) gc trigger (Mb) limit (Mb) max used (Mb)
## Ncells 526537 28.2    1169750 62.5         NA   669282 35.8
## Vcells 971218  7.5    8388608 64.0      32768  1840402 14.1
cat("\f")         # Clear the console
graphics.off()    # Clear graphs
prior       <-  c( 0.35, 0.2, 0.45 ) # marginal probabilities given in the question stored in a vector
likelihood  <-  c( 0.25, 0.7, 0.05 ) # conditional probabilities vector stored in a vector
posterior   <-  prior   *   likelihood
posterior
## [1] 0.0875 0.1400 0.0225
bayesian    <-  posterior / sum(posterior)
bayesian[2]                          # for event A_2
## [1] 0.56

Standard Approach (Tree Diagram)

3 Installation

See installation help if required.

rm(list=ls())       # empty environment
sessionInfo()
## R version 4.2.1 (2022-06-23)
## Platform: x86_64-apple-darwin17.0 (64-bit)
## Running under: macOS Big Sur ... 10.16
## 
## Matrix products: default
## BLAS:   /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRblas.0.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRlapack.dylib
## 
## locale:
## [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## loaded via a namespace (and not attached):
##  [1] digest_0.6.32   R6_2.5.1        jsonlite_1.8.7  evaluate_0.21  
##  [5] cachem_1.0.8    rlang_1.1.1     cli_3.6.1       rstudioapi_0.14
##  [9] jquerylib_0.1.4 bslib_0.5.0     rmarkdown_2.21  tools_4.2.1    
## [13] xfun_0.39       yaml_2.3.7      fastmap_1.1.1   compiler_4.2.1 
## [17] htmltools_0.5.5 knitr_1.42      sass_0.4.6
# install.packages("BiocManager")
library(BiocManager)
## Bioconductor version '3.15' is out-of-date; the current release version '3.17'
##   is available with R version '4.3'; see https://bioconductor.org/install
BiocManager::install("Rgraphviz")
## Bioconductor version 3.15 (BiocManager 1.30.19), R 4.2.1 (2022-06-23)
## Warning: package(s) not installed when version(s) same as or greater than current; use
##   `force = TRUE` to re-install: 'Rgraphviz'
## Old packages: 'BayesFactor', 'BiocManager', 'bnlearn', 'bslib', 'cpp11',
##   'curl', 'cvms', 'digest', 'distributional', 'DT', 'EnvStats', 'evaluate',
##   'fable', 'fabletools', 'fansi', 'fastDummies', 'fastmatch', 'feasts',
##   'fontawesome', 'forecast', 'fs', 'geometries', 'ggplot2', 'glmmML', 'gmp',
##   'gptstudio', 'groupdata2', 'gtable', 'htmltools', 'httr2', 'ipumsr', 'ks',
##   'lavaan', 'leafem', 'leaflet', 'leaflet.providers', 'lubridate', 'magick',
##   'Matrix', 'openssl', 'osqp', 'pak', 'permutations', 'polyclip', 'pROC', 'ps',
##   'psych', 'Rfast', 'rgdal', 'rgeos', 'rmarkdown', 'ROI', 'ROI.plugin.qpoases',
##   'rticles', 'sass', 'sfheaders', 'spatialreg', 'spatstat.explore',
##   'spatstat.geom', 'spatstat.random', 'spatstat.sparse', 'spData', 'survey',
##   'systemfit', 'timetk', 'tinytex', 'tmap', 'tseries', 'tsfeatures', 'UBL',
##   'usmap', 'vars', 'xfun', 'xml2', 'acepack', 'animint2', 'askpass',
##   'bayestestR', 'blob', 'bookdown', 'broom', 'broom.helpers', 'cachem', 'car',
##   'checkmate', 'chron', 'Ckmeans.1d.dp', 'class', 'classInt', 'cli', 'clock',
##   'codetools', 'coin', 'collapse', 'colourpicker', 'commonmark', 'covr',
##   'credentials', 'crul', 'Cubist', 'cyclocomp', 'data.table', 'datamods',
##   'datawizard', 'dbplyr', 'deldir', 'DEoptimR', 'DiagrammeR', 'dials',
##   'directlabels', 'downlit', 'dplyr', 'dtplyr', 'e1071', 'earth', 'ellipse',
##   'emmeans', 'expss', 'FactoMineR', 'fastmap', 'flextable', 'float', 'forcats',
##   'foreign', 'Formula', 'ftExtra', 'future', 'future.apply', 'gam', 'gamlss',
##   'gamlss.dist', 'gargle', 'gdtools', 'gert', 'ggbeeswarm', 'ggcorrplot',
##   'ggExtra', 'ggfortify', 'ggiraph', 'ggpubr', 'ggrepel', 'ggsci', 'gh',
##   'glmnet', 'googledrive', 'googlesheets4', 'googleVis', 'GPArotation',
##   'gstat', 'gt', 'gtExtras', 'gtsummary', 'hardhat', 'haven', 'HistData',
##   'Hmisc', 'hms', 'htmlwidgets', 'httpuv', 'httr', 'igraph', 'infer',
##   'influenceR', 'insight', 'interp', 'intervals', 'ipred', 'janitor',
##   'jsonlite', 'kernlab', 'KernSmooth', 'klaR', 'knitr', 'labeling', 'labelled',
##   'later', 'lattice', 'lava', 'libcoin', 'lintr', 'lme4', 'logr', 'lwgeom',
##   'maptools', 'markdown', 'MASS', 'MatrixModels', 'matrixStats', 'mda', 'mgcv',
##   'mice', 'minqa', 'miscTools', 'mlbench', 'modeldata', 'modelenv', 'modelr',
##   'modelsummary', 'multcomp', 'multcompView', 'mvtnorm', 'nlme', 'nnet',
##   'norm', 'officer', 'openxlsx', 'packrat', 'parallelly', 'parameters',
##   'parsnip', 'party', 'patchwork', 'pbapply', 'performance', 'pillar',
##   'pkgbuild', 'pkgload', 'plm', 'plotly', 'pls', 'plyr', 'polspline',
##   'prettyunits', 'processx', 'prodlim', 'profvis', 'progressr', 'promises',
##   'pscl', 'psychTools', 'purrr', 'qqconf', 'quantmod', 'quantreg', 'quarto',
##   'questionr', 'qvcalc', 'ranger', 'raster', 'rbibutils', 'Rcpp',
##   'RcppArmadillo', 'RcppTOML', 'Rcsdp', 'RCurl', 'Rdpack', 'reactable',
##   'readr', 'readsdmx', 'readxl', 'recipes', 'rematch', 'remotes',
##   'ResourceSelection', 'reticulate', 'rio', 'rlang', 'rms', 'RobStatTM',
##   'robustbase', 'rpart', 'RPEGLMEN', 'rrcov', 'rsample', 'rsconnect',
##   'rstatix', 'rstudioapi', 's2', 'scatterplot3d', 'sf', 'shiny',
##   'shinyWidgets', 'SMOTEWB', 'snakecase', 'sourcetools', 'sp', 'spacetime',
##   'spatial', 'stars', 'styler', 'subselect', 'survival', 'sys', 'systemfonts',
##   'tables', 'terra', 'testthat', 'textshaping', 'TH.data', 'themis',
##   'this.path', 'tibble', 'tidymodels', 'tidyverse', 'tinytest',
##   'TraMineRextras', 'triebeard', 'tune', 'twosamples', 'tzdb', 'units',
##   'usethis', 'utf8', 'uuid', 'V8', 'vcd', 'vctrs', 'VGAM', 'viridis',
##   'viridisLite', 'vroom', 'waldo', 'webshot', 'withr', 'wk', 'wooldridge',
##   'workflows', 'workflowsets', 'xgboost', 'xts', 'yardstick', 'zip', 'zoo'
require("Rgraphviz")
## Loading required package: Rgraphviz
## Loading required package: graph
## Loading required package: BiocGenerics
## 
## Attaching package: 'BiocGenerics'
## The following objects are masked from 'package:stats':
## 
##     IQR, mad, sd, var, xtabs
## The following objects are masked from 'package:base':
## 
##     anyDuplicated, append, as.data.frame, basename, cbind, colnames,
##     dirname, do.call, duplicated, eval, evalq, Filter, Find, get, grep,
##     grepl, intersect, is.unsorted, lapply, Map, mapply, match, mget,
##     order, paste, pmax, pmax.int, pmin, pmin.int, Position, rank,
##     rbind, Reduce, rownames, sapply, setdiff, sort, table, tapply,
##     union, unique, unsplit, which.max, which.min
## Loading required package: grid
BiocManager::valid()     ## R version 3.5 or later
## Warning: 336 packages out-of-date; 2 packages too new
## 
## * sessionInfo()
## 
## R version 4.2.1 (2022-06-23)
## Platform: x86_64-apple-darwin17.0 (64-bit)
## Running under: macOS Big Sur ... 10.16
## 
## Matrix products: default
## BLAS:   /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRblas.0.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRlapack.dylib
## 
## locale:
## [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
## 
## attached base packages:
## [1] grid      stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
## [1] Rgraphviz_2.40.0    graph_1.74.0        BiocGenerics_0.42.0
## [4] BiocManager_1.30.19
## 
## loaded via a namespace (and not attached):
##  [1] digest_0.6.32   R6_2.5.1        jsonlite_1.8.7  stats4_4.2.1   
##  [5] evaluate_0.21   cachem_1.0.8    rlang_1.1.1     cli_3.6.1      
##  [9] rstudioapi_0.14 jquerylib_0.1.4 bslib_0.5.0     rmarkdown_2.21 
## [13] tools_4.2.1     xfun_0.39       yaml_2.3.7      fastmap_1.1.1  
## [17] compiler_4.2.1  htmltools_0.5.5 knitr_1.42      sass_0.4.6     
## 
## Bioconductor version '3.15'
## 
##   * 336 packages out-of-date
##   * 2 packages too new
## 
## create a valid installation with
## 
##   BiocManager::install(c(
##     "acepack", "animint2", "askpass", "BayesFactor", "bayestestR",
##     "BiocManager", "blob", "bnlearn", "bookdown", "broom", "broom.helpers",
##     "bslib", "cachem", "car", "checkmate", "chron", "Ckmeans.1d.dp",
##     "classInt", "cli", "clock", "coin", "collapse", "colourpicker",
##     "commonmark", "covr", "cpp11", "credentials", "crul", "Cubist", "curl",
##     "cvms", "cyclocomp", "data.table", "datamods", "datawizard", "dbplyr",
##     "deldir", "DEoptimR", "DiagrammeR", "dials", "digest", "directlabels",
##     "distributional", "downlit", "dplyr", "DT", "dtplyr", "e1071", "earth",
##     "ellipse", "emmeans", "EnvStats", "evaluate", "expss", "fable",
##     "fabletools", "FactoMineR", "fansi", "fastDummies", "fastmap", "fastmatch",
##     "feasts", "flextable", "float", "fontawesome", "forcats", "forecast",
##     "Formula", "fs", "ftExtra", "future", "future.apply", "gam", "gamlss",
##     "gamlss.dist", "gargle", "gdtools", "geometries", "gert", "ggbeeswarm",
##     "ggcorrplot", "ggExtra", "ggfortify", "ggiraph", "ggplot2", "ggpubr",
##     "ggrepel", "ggsci", "gh", "glmmML", "glmnet", "gmp", "googledrive",
##     "googlesheets4", "googleVis", "GPArotation", "gptstudio", "groupdata2",
##     "gstat", "gt", "gtable", "gtExtras", "gtsummary", "hardhat", "haven",
##     "HistData", "Hmisc", "hms", "htmltools", "htmlwidgets", "httpuv", "httr",
##     "httr2", "igraph", "infer", "influenceR", "insight", "interp", "intervals",
##     "ipred", "ipumsr", "janitor", "jsonlite", "kableExtra", "kernlab", "klaR",
##     "knitr", "ks", "labeling", "labelled", "later", "lava", "lavaan", "leafem",
##     "leaflet", "leaflet.providers", "libcoin", "lintr", "lme4", "logr",
##     "lubridate", "lwgeom", "magick", "maptools", "markdown", "MatrixModels",
##     "matrixStats", "mda", "mice", "minqa", "miscTools", "mlbench", "modeldata",
##     "modelenv", "modelr", "modelsummary", "multcomp", "multcompView",
##     "mvtnorm", "norm", "officer", "openssl", "openxlsx", "osqp", "packrat",
##     "pak", "parallelly", "parameters", "parsnip", "party", "patchwork",
##     "pbapply", "performance", "permutations", "pillar", "pkgbuild", "pkgload",
##     "plm", "plotly", "pls", "plyr", "polspline", "polyclip", "prettyunits",
##     "pROC", "processx", "prodlim", "profvis", "progressr", "promises", "ps",
##     "pscl", "psych", "psychTools", "purrr", "qqconf", "quantmod", "quantreg",
##     "quarto", "questionr", "qvcalc", "ranger", "raster", "rbibutils", "Rcpp",
##     "RcppArmadillo", "RcppTOML", "Rcsdp", "RCurl", "Rdpack", "reactable",
##     "readr", "readsdmx", "readxl", "recipes", "rematch", "remotes",
##     "ResourceSelection", "reticulate", "Rfast", "rgdal", "rgeos", "rio",
##     "rlang", "rmarkdown", "rms", "RobStatTM", "robustbase", "ROI",
##     "ROI.plugin.qpoases", "RPEGLMEN", "rrcov", "rsample", "rsconnect",
##     "rstatix", "rstudioapi", "rticles", "s2", "sass", "scatterplot3d", "sf",
##     "sfheaders", "shiny", "shinyWidgets", "SMOTEWB", "snakecase",
##     "sourcetools", "sp", "spacetime", "spatialreg", "spatstat.explore",
##     "spatstat.geom", "spatstat.random", "spatstat.sparse", "spData", "stars",
##     "styler", "subselect", "survey", "sys", "systemfit", "systemfonts",
##     "tables", "terra", "testthat", "textshaping", "TH.data", "themis",
##     "this.path", "tibble", "tidymodels", "tidyverse", "timetk", "tinytest",
##     "tinytex", "tmap", "TraMineRextras", "triebeard", "tseries", "tsfeatures",
##     "tsibbledata", "tune", "twosamples", "tzdb", "UBL", "units", "usethis",
##     "usmap", "utf8", "uuid", "V8", "vars", "vcd", "vctrs", "VGAM", "viridis",
##     "viridisLite", "vroom", "waldo", "webshot", "withr", "wk", "wooldridge",
##     "workflows", "workflowsets", "xfun", "xgboost", "xml2", "xts", "yardstick",
##     "zip", "zoo"
##   ), update = TRUE, ask = FALSE, force = TRUE)
## 
## more details: BiocManager::valid()$too_new, BiocManager::valid()$out_of_date

If you still need to install the Rgraphviz, please open the .Rmd file and see code here (not printed in output).

4 ADAPTED CODE (3 Branches)

We will break out code into three parts - input, output and graph setup.

4.1 1. INPUT

Note the notation is slightly different form the textbook example though.

# Marginal Probability of a1(academic events) / a2(sports events) / a3(no events) 

a1            <- 0.35
a2            <- 0.2
a3            <- 0.45



# Conditional Probability P(b | a)    

b1_no_park_given_a1     <- 0.25   # b1_no_park is garage full 
b1_no_park_given_a2     <- 0.70   
# thus, b2_with_park_XX is garage empty / not full 

b1_no_park_given_a3     <- .05
# On evenings when there are no events, it only fills up about 5% of the time.

4.2 2. OUTPUT

# Everything below here will be calculated

## complements 
b2_with_park_given_a1   <- 1 - b1_no_park_given_a1
b2_with_park_given_a2   <- 1 - b1_no_park_given_a2
b2_with_park_given_a3   <- 1 - b1_no_park_given_a3 

## Incorrect 
# b2_with_park_given_a3   <- 1 - b2_with_park_given_a1 - b2_with_park_given_a2 
# b1_no_park_given_a3     <- 1 - b2_with_park_given_a3   


# Calculate the rest of the values based upon the 3 variables above

probability_b1_no_park_given_a1   <-  a1  *   b1_no_park_given_a1
probability_b2_with_park_given_a1 <-  a1  *   b2_with_park_given_a1

probability_b1_no_park_given_a2   <-  a2  *   b1_no_park_given_a2
probability_b2_with_park_given_a2 <-  a2  *   b2_with_park_given_a2

probability_b1_no_park_given_a3   <-  a3  *   b1_no_park_given_a3
probability_b2_with_park_given_a3 <-  a3  *   b2_with_park_given_a3

4.3 3. GRAPH SETUP

# These are the labels of the nodes on the graph

node1 <-  "Campus has"
node2 <-  "Academic Event"
node3 <-  "Sporting Event"
node4 <-  "No Event"
node5 <-  "AE & Garage Full"
node6 <-  "AE & Garage Not Full"
node7 <-  "SE & Garage Full"
node8 <-  "SE & Garage Not Full"
node9 <-  "NE & Garage Full"
node10 <- "NE & Garage Not Full"

nodeNames<-c(node1, node2, node3, node4, node5, node6, node7, node8, node9, node10)

 
?new # A call to a generating function for a class (see setClass) will pass its ... arguments to a corresponding call to new().
rEG <- new("graphNEL", 
           nodes = nodeNames, 
           edgemode="directed"
           )



# Draw the "lines" or "branches" of the probability Tree

rEG <- addEdge(nodeNames[1], nodeNames[2], rEG, 1)
rEG <- addEdge(nodeNames[1], nodeNames[3], rEG, 1)
rEG <- addEdge(nodeNames[1], nodeNames[4], rEG, 1)
rEG <- addEdge(nodeNames[2], nodeNames[5], rEG, 1)
rEG <- addEdge(nodeNames[2], nodeNames[6], rEG, 1)
rEG <- addEdge(nodeNames[3], nodeNames[7], rEG, 1)
rEG <- addEdge(nodeNames[3], nodeNames[8], rEG, 1)
rEG <- addEdge(nodeNames[4], nodeNames[9], rEG, 1)
rEG <- addEdge(nodeNames[4], nodeNames[10], rEG, 10)

 

eAttrs <- list()

 

q<-edgeNames(rEG)

 

# Add the probability values to the the branch lines


eAttrs$label <- c(toString(a1),toString(a2), toString(a3),
 toString(b1_no_park_given_a1), toString(b2_with_park_given_a1),
 toString(b1_no_park_given_a2), toString(b2_with_park_given_a2),
 toString(b1_no_park_given_a3), toString(b2_with_park_given_a3)
 )

names(eAttrs$label) <- c(q[1],q[2], q[3], q[4], q[5], q[6], q[7],q[8],q[9])
edgeAttrs<-eAttrs

 

# Set the color, etc, of the tree

attributes<-list(node=list(label="foo", fillcolor="lightgreen", fontsize="15"),
edge=list(color="red"),graph=list(rankdir="LR"))

 

#Plot the probability tree using Rgraphvis
plot(rEG, edgeAttrs=eAttrs, attrs=attributes)

nodes(rEG)
##  [1] "Campus has"           "Academic Event"       "Sporting Event"      
##  [4] "No Event"             "AE & Garage Full"     "AE & Garage Not Full"
##  [7] "SE & Garage Full"     "SE & Garage Not Full" "NE & Garage Full"    
## [10] "NE & Garage Not Full"
edges(rEG)
## $`Campus has`
## [1] "Academic Event" "Sporting Event" "No Event"      
## 
## $`Academic Event`
## [1] "AE & Garage Full"     "AE & Garage Not Full"
## 
## $`Sporting Event`
## [1] "SE & Garage Full"     "SE & Garage Not Full"
## 
## $`No Event`
## [1] "NE & Garage Full"     "NE & Garage Not Full"
## 
## $`AE & Garage Full`
## character(0)
## 
## $`AE & Garage Not Full`
## character(0)
## 
## $`SE & Garage Full`
## character(0)
## 
## $`SE & Garage Not Full`
## character(0)
## 
## $`NE & Garage Full`
## character(0)
## 
## $`NE & Garage Not Full`
## character(0)
# Add the probability values to the leaves of tree



 text(450,380,probability_b1_no_park_given_a1, cex=.8)
# text(450,250,probability_b2_with_park_given_a1, cex=.8)
 text(450,250,probability_b1_no_park_given_a2, cex=.8)
# text(450,150,probability_b2_with_park_given_a2, cex=.8)
 text(450,120,probability_b1_no_park_given_a3,cex=.8)

# text(450,30, probability_b2_with_park_given_a3,cex=.8)
answer <- probability_b1_no_park_given_a2   / (probability_b1_no_park_given_a1+probability_b1_no_park_given_a2+probability_b1_no_park_given_a3)

answer 
## [1] 0.56

5 ORIGINAL CODE (2 Branches)

5.1 1. INPUT

# Change the three variables below to match your actual values
# These are the values that you can change for your own probability tree
# From these three values, other probabilities (e.g. prob(b)) will be calculated 

# Probability of a
a             <-  .20

# Probability (b | a)
bGivena       <-  .70

# Probability (b | ¨a)
bGivenNota    <-  .30

5.2 2. OUTPUT

# Calculate the rest of the values based upon the 3 variables above
notA          <-    1 - a                   # Negation of a, and so on...
notbGivena    <-    1 - bGivena
notbGivenNota <-    1 - bGivenNota

# Joint Probabilities of a and B, a and notb, nota and b, nota and notb
aANDb         <-  a   *   bGivena
aANDnotb      <-  a   *   notbGivena
notaANDb      <- notA *   bGivenNota
notaANDnotb   <- notA *   notbGivenNota

# Probability of B
b             <-  aANDb   +   notaANDb
notB          <-  1 - b

# Bayes theorum - probabiliyt of A | B
# Prob (a | b) = Prob (a AND b) / prob (b)
aGivenb       <-  aANDb / b

5.3 3. GRAPH SETUP

# These are the labels of the nodes on the graph
# To signify "Not A" - we use A' or A prime 

# Erase any existing plots if you want to redraw  
# dev.off()

node1   <-  "P"
node2   <-  "A"
node3   <-  "A'"
node4   <-  "A&B"
node5   <-  "A&B'"
node6   <-  "A'&B"
node7   <-  "A'&B'"

nodeNames   <-  c(node1,node2,node3,node4, node5,node6, node7)
rEG     <-  new("graphNEL", nodes=nodeNames, edgemode="directed")
rEG
## A graphNEL graph with directed edges
## Number of Nodes = 7 
## Number of Edges = 0
# Draw the "lines" or "branches" of the probability Tree
rEG <- addEdge(nodeNames[1], nodeNames[2], rEG, 1)
rEG <- addEdge(nodeNames[1], nodeNames[3], rEG, 1)
rEG <- addEdge(nodeNames[2], nodeNames[4], rEG, 1)
rEG <- addEdge(nodeNames[2], nodeNames[5], rEG, 1)
rEG <- addEdge(nodeNames[3], nodeNames[6], rEG, 1)
rEG <- addEdge(nodeNames[3], nodeNames[7], rEG, 10)

eAttrs <- list()

q<-edgeNames(rEG)

# Add the probability values to the the branch lines

eAttrs$label <- c(toString(a),toString(notA),
                  toString(bGivena), toString(notbGivena),
                  toString(bGivenNota), toString(notbGivenNota))
names(eAttrs$label) <- c(q[1],q[2], q[3], q[4], q[5], q[6])
edgeAttrs<-eAttrs

# Set the color, etc, of the tree
attributes  <-  list(node=list(label="foo", fillcolor="lightgreen", fontsize="15"),
                 edge=list(color="red"),graph=list(rankdir="LR"))



# Plot the probability tree using Rgraphvis
plot(rEG, edgeAttrs=eAttrs, attrs=attributes)
nodes(rEG)
## [1] "P"     "A"     "A'"    "A&B"   "A&B'"  "A'&B"  "A'&B'"
edges(rEG)
## $P
## [1] "A"  "A'"
## 
## $A
## [1] "A&B"  "A&B'"
## 
## $`A'`
## [1] "A'&B"  "A'&B'"
## 
## $`A&B`
## character(0)
## 
## $`A&B'`
## character(0)
## 
## $`A'&B`
## character(0)
## 
## $`A'&B'`
## character(0)
#Add the probability values to the leaves of A&B, A&B', A'&B, A'&B'
text(500,420,aANDb, cex=.8)
text(500,280,aANDnotb,cex=.8)
text(500,160,notaANDb,cex=.8)
text(500,30,notaANDnotb,cex=.8)
text(340,440,"(B | A)",cex=.8)
text(340,230,"(B | A')",cex=.8)

#Write a table in the lower left of the probablites of A and B
text(80,50,paste("P(A):",a),cex=.9, col="darkgreen")
text(80,20,paste("P(A'):",notA),cex=.9, col="darkgreen")

text(160,50,paste("P(B):",round(b,digits=2)),cex=.9)
text(160,20,paste("P(B'):",round(notB, 2)),cex=.9)

text(80,420,paste("P(A|B): ",round(aGivenb,digits=2)),cex=.9,col="blue")