[英]Apply binom.test to every row using columns as arguments?
我意識到以前曾問過這種問題,但我不明白為什么我的代碼會中斷。
我已經嘗試mapply
單獨使用mapply
並與do.call
以及purrr
包的pmap
函數一起使用。 我不斷收到“未使用的論據”錯誤。 由於所有3個都失敗,因此我認為我必須在參數中錯誤地引用了我的數據。 我已經使用mdply
包中的plyr
來做類似的事情,但這已經一年多了。 當然,任何替代方法也將被贊賞。
要創建數據compar
,請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.call
和mapply
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]])
列名與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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.