1

I have a set of Bernoulli variables, giving specific values with different probabilities. The variables are independent. I'm trying to build a simple discrete probability table for all the possible outcomes. A short example of the data I have is:

# A tibble: 2 x 4
  `test number`  prob value `no-value`
          <dbl> <dbl> <dbl>      <dbl>
1             1   0.7   1.7        0.3
2             2   0.6   1.5        0.6

Where the value is the sum of the possible values and the probability is the probability of this value. The example I'm using is from an excel sheet. The table I'm working on is a long list of independent tests. Each test has a possible value for success, a probability for success and a value for no success (with a probability of (1 - probability of success)). The probability table is a table that calculates the probability for each possible outcome - possible values (summing the values for that outcome) and the probability for that outcome. So the first possible outcome 3.2 = 1.7 + 1.5 has a probability of 0.42 = 0.7 * 0.6. The second outcome is 2.3 = (1.7 + 0.6) with a probability of 0.28 = (0.7 * (1 - 0.6) and so on.

So the solution I'm trying to get is something like this (2.29 = 2.3, 0.899 = 0.9:

# A tibble: 1 x 5
  value       `3.2` `2.299999999999999~ `1.8` `0.8999999999999999~
  <chr>       <dbl>               <dbl> <dbl>                <dbl>
1 probability  0.42               0.280  0.18                 0.12
Seif
  • 82
  • 1
  • 8
Amidavid
  • 177
  • 7

1 Answers1

1

Here is a way:

dat <- data.frame(
  prob = c(0.3, 0.7, 0.6),
  value_success = c(1, 2, 3),
  value_failure = c(4, 5, 6)
)

ntrials <- nrow(dat)

issues <- setNames(
  do.call(expand.grid, replicate(ntrials, c(0,1), simplify = FALSE)),
  paste0("trial", 1:ntrials)
)

issues[["prob"]] <- apply(issues, 1, function(x){
  prod(ifelse(x==0, 1-dat$prob, dat$prob))
})

issues[["total"]] <- apply(issues[,1:ntrials], 1, function(x){
  sum(ifelse(x==0, dat$value_failure, dat$value_success))
})

issues
#   trial1 trial2 trial3  prob total
# 1      0      0      0 0.084    15
# 2      1      0      0 0.036    12
# 3      0      1      0 0.196    12
# 4      1      1      0 0.084     9
# 5      0      0      1 0.126    12
# 6      1      0      1 0.054     9
# 7      0      1      1 0.294     9
# 8      1      1      1 0.126     6
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225