【问题标题】:binomial test in R using by() on data.frame在 data.frame 上使用 by() 在 R 中进行二项式检验
【发布时间】:2012-12-07 22:07:36
【问题描述】:

我对@9​​87654321@ 在by 选项中使用时的行为感到困惑。

它似乎不适用于某些数据帧,但适用于我放在一起的一些虚拟数据。

调用mean() 可以正常工作...

我的示例代码如下。


#####  this does not work...

bug <- InsectSprays   
bug$outcome <- ifelse(bug$count > 4, 1, 2 )
bug$spray.n <- ifelse(bug$spray == "A", 1,
               ifelse(bug$spray == "B", 2,
               ifelse(bug$spray == "C", 3,
               ifelse(bug$spray == "D", 4,
               ifelse(bug$spray == "E", 5, 6)))))

binom.test(table(bug$outcome), alternative="greater")               
by(bug, bug$spray.n, FUN = function(X) binom.test(table(X$outcome),
  alternative="greater" ))
by(bug, bug$spray.n, FUN = function(X) mean(X$count)                             

#####  this works...

#####  generating example data
#####  this has three groups, each with a binomial indicator
#####  success is coded as 1, failure as a 0

set.seed(271828)
center <- gl(3,10)
outcome <- rbinom(length(center), 1, .6777)
id <- seq(1,length(center),1)
dat <- as.data.frame(cbind(center,id,outcome))

#####  have to recode success and failure to use table()  
#####  !!!!! would like to avoid having to do this...

dat$primary <- ifelse(dat$outcome == 1 , 1 , 2)
dat$cent <- as.factor(dat$center)

##### carrying out one sided binomial test for positive outcome

binom.test(table(dat$primary), alternative = "greater" )

#####  would like to carry out the same test by center...

by(dat, dat$center, FUN = function(X) binom.test(table(X$primary), 
  alternative = "greater"))
by(dat, dat$center, FUN = function(X) mean(X$outcome))

【问题讨论】:

  • 如果您尝试,您可能会看到问题:by(bug, bug$spray.n, FUN = function(X) table(X$outcome))
  • 在没有警告或评论的情况下溜进rm( list=ls() )是不礼貌的。
  • @DWin 抱歉,趁我没注意的时候偷偷溜进来……

标签: r function apply


【解决方案1】:

某些binom.test 调用不起作用的原因是某些组全部成功(或失败)。因此,您需要在每组中至少有两个级别才能进行测试(这很有意义......)。


为了完整性:

           #####  this does work...

           air <- airquality
           air

           air$outcome <- ifelse(air$Wind > 10, 1, 2 )


           binom.test(table(air$outcome), alternative="greater")



           by(air, air$Month, FUN = function(X) mean(X$Wind))

           by(air, air$Month, FUN = function(X) table(X$outcome))

           by(air, air$Month, FUN = function(X) binom.test(table(X$outcome), alternative="greater"))

【讨论】:

  • +1 您的额外解释使其对其他人更有用。
【解决方案2】:

你可以试试看问题:

by(bug, bug$spray.n, FUN = function(X) table(X$outcome))

【讨论】:

    猜你喜欢
    • 2017-11-09
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 2018-02-28
    • 2015-09-17
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    相关资源
    最近更新 更多