everestial
everestial

Reputation: 7255

How to run binomial test for each row of R dataframe?

I am tyring to calculate the p-value dbinom() for each row or R Dataframe

data =

small    Sum
2         7
3         6
5         11

For each row I can do:

> binom.test(2, 7, 0.5, alternative=c("two.sided"), conf.level = 0.95)

Exact binomial test

data:  2 and 7
number of successes = 2, number of trials = 7, p-value = 0.4531
alternative hypothesis: true probability of success is not equal to 0.5
95 percent confidence interval:
0.03669257 0.70957914
   sample estimates:
   probability of success 
         0.2857143

But, I am not having success to apply it to all the rows.

Something like:

counts$pVal <- 2*sum(dbinom(0:counts$small, counts$Sum, 0.5))

#or,
counts_2ms04h$pVal <- binom.test(0:counts$small, counts$Sum, 0.5, alternative=c("two.sided"), conf.level = 0.99)


## I also used tapply
test <- function(x, n, p){binom.test(x, n, p, alternative="two-sided")}
mapply(test, counts$small, counts$Sum, 0.5)

Error in binom.test(x, n, p, alternative = "two-sided") : 
  'n' must be a positive integer >= 'x' 

Thanks,

Upvotes: 1

Views: 2526

Answers (2)

kashiff007
kashiff007

Reputation: 386

What is the problem with running dbinom directly.

counts$pVal <- dbinom(count$small, count$Sum, 0.5)

Upvotes: 0

Edgar Santos
Edgar Santos

Reputation: 3504

How about:

bt <- function(a, b, p = 0.5) {binom.test(a, b, 0.5, alternative=
                            c("two.sided"), conf.level = 0.95)$p.value}
counts$pVal <- mapply(bt, counts$small, counts$Sum)

  small Sum     pVal
1     2   7 0.453125
2     3   6 1.000000
3     5  11 1.000000

Upvotes: 4

Related Questions