【问题标题】:Apply binom.test to every row using columns as arguments?使用列作为参数将 binom.test 应用于每一行?
【发布时间】:2018-04-08 00:16:43
【问题描述】:

我意识到以前有人问过这种问题,但我不明白为什么我的代码会出错。

我已经单独尝试过mapplydo.call 以及purrr 包的pmap 函数。我不断收到“未使用的参数”错误。由于所有 3 个都失败,我认为我必须在参数中错误地引用我的数据。我已经使用plyr 包中的mdply 来做这样的事情,但那是一年多以前的事了。当然,任何替代方法也会受到赞赏。

要创建数据框,compar:

obs = floor(runif(500, 1,99))
p = round(runif(500,0,1), digits = 4)
n = floor(runif(500, 100,150))
test = rep("two.sided", 500)
conf = rep(0.95, 500)

compar = as.data.frame(cbind(obs,n, p))    
compar$test = test
compar$conf = conf
head(compar, 3)
  obs      p   n      test conf
1  47 0.2432 133 two.sided 0.95
2  52 0.3391 118 two.sided 0.95
3  22 0.2790 115 two.sided 0.95

我试试pmap:

pmap(.l = compar, .f = binom.test)
Error in .f(obs = .l[[c(1L, i)]], p = .l[[c(2L, i)]], n = .l[[c(3L, i)]],  : 
  unused arguments (obs = .l[[c(1, i)]], test = .l[[c(4, i)]])

接下来,mapply

mapply(compar, FUN = binom.test)
Error in (function (x, n, p = 0.5, alternative = c("two.sided", "less",  : 
  incorrect length of 'x'

最后,do.callmapply

do.call(mapply, c(binom.test, compar[c("obs", "n", "p", "test", "conf")]))
Error in (function (x, n, p = 0.5, alternative = c("two.sided", "less",  : 
  unused arguments (obs = dots[[1]][[1]], test = dots[[4]][[1]])

【问题讨论】:

    标签: r plyr purrr mapply do.call


    【解决方案1】:

    列名与binom.test 参数不匹配;对于pmap 版本,根据binom.test 参数重命名列应该可以:

    pmap(select(compar, x=obs, n, p, alternative=test, conf), binom.test)
    
    #[[1]]
    
    #   Exact binomial test
    
    #data:  .l[[c(1L, i)]] and .l[[c(2L, i)]]
    #number of successes = 5, number of trials = 149, p-value < 2.2e-16
    #alternative hypothesis: true probability of success is not equal to 0.435
    #95 percent confidence interval:
    # 0.01098400 0.07657136
    #sample estimates:
    #probability of success 
    #            0.03355705 
    
    
    #[[2]]
    
    #   Exact binomial test
    
    #data:  .l[[c(1L, i)]] and .l[[c(2L, i)]]
    #number of successes = 20, number of trials = 113, p-value = 1.391e-10
    #alternative hypothesis: true probability of success is not equal to 0.4681
    #95 percent confidence interval:
    # 0.1115928 0.2600272
    #sample estimates:
    #probability of success 
    #             0.1769912 
    
    # more output
    

    或者:pmap(rename(compar, x=obs, alternative=test), binom.test)

    【讨论】:

    • 啊,我认为 pmap 会尊重位置,而不是列名。这就说得通了。我会用我的实际数据来试试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    相关资源
    最近更新 更多