2017-06-22 40 views
-1

我tyring计算p-valuedbinom()的每一行或R Dataframe如何为R数据框的每一行运行二项式测试?

数据=

small Sum 
2   7 
3   6 
5   11 

对于每一行,我可以这样做:

> 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 

但是,我没有成功将其应用于所有行。

喜欢的东西:

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' 

感谢,

回答

1

如何:

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