使用列作为参数将binom.test应用于每一行?

时间:2018-04-08 00:16:43

标签: r plyr purrr mapply do.call

我意识到此前已经提出过这样的问题,但我不明白为什么我的代码会破坏。

我已尝试mapply单独使用do.call以及purrr包的pmap功能。我不断得到“未使用的参数”错误。由于所有3个都在失败,我想我必须在参数中错误地引用我的数据。我使用mdply包中的plyr做了类似的事情,但那是一年多以前的事了。当然,任何替代方法也会受到赞赏。

要创建数据框,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]])

1 个答案:

答案 0 :(得分: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)