user6644063
user6644063

Reputation:

Multiple binomial tests in one code

I would like to perform the exact binomial test, with binom R package(binom.test function), to 4 different number of successes with 4 different probability values.

I can do it singularly, but I would like to know if I can write a code to do the calculation in only one command (e.g. lapply, for loop).

x <- c(68, 69, 70, 75)  #number of successes
p <- c(1/365, 2/365, 3/365, 4/365)  #probability of success
n <- 265 #number of trials

The conf.level = 0.95 and alternative = "two.sided" (as the outcome can be as 1 or 0).

Any suggestion?


I tried:

for (i in 1:4) {
     test[i] <- binom.test(x[i], n, p[i], alternative = "two.sided", conf.level = 0.95)
      }

but doesn't work.

Upvotes: 2

Views: 1922

Answers (2)

snaut
snaut

Reputation: 2535

Use mapply:

mapply(binom.test, x, p, n=n, alternative = "two.sided", conf.level = 0.95, SIMPLIFY = FALSE)

mapply just calls the function in its first argument with all the values in its additional arguments and additional named parameters. (See help for the mapply function)

If you want just one field of the result, you could call mapply like this:

mapply(function(x,p,n, ...){
         binom.test(x, n, p, ...)$p.value
       },
       x, p, n=n, alternative = "two.sided", conf.level = 0.95)

Upvotes: 1

elmo
elmo

Reputation: 325

If you are interested only in the resulting p-values, here is what you can do:

x <- c(68, 69, 70, 75)  #number of successes
p <- c(1/365, 2/365, 3/365, 4/365)  #probability of success
n <- 265 #number of trials
test <- numeric(4)

for (i in 1:4) {
  test[i] <- binom.test(x[i], n, p[i], alternative = "two.sided", conf.level = 0.95)$p.value
}

test
[1] 6.621447e-111  1.801758e-92  3.467288e-82  2.442975e-81

Upvotes: 1

Related Questions