Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster looped binom.test?

Tags:

r

I have a vector of successes, and want to conduct a binom.test on each of the values. Is there a faster method than this loop (I have quite alot):

successes <-rbinom(100, 625, 1/5)
x <-NULL
for (i in 1:100) {
x <-append(x, binom.test(successes[i], 625, 1/5)$p.value)
}
like image 566
biggob1 Avatar asked Dec 11 '22 16:12

biggob1


1 Answers

Instead of for loop you can use sapply() to calculate p.values for each value of successes.

pp <- sapply(successes, function(x) binom.test(x, 625, 1/5)$p.value)

If you need real speed-up of process you can use advantages of package data.table. First, convert successes to data.table object. Then calculate for each row p.value.

library(data.table)
dt<-data.table(successes)
dt[,pp:=binom.test(successes, 625, 1/5)$p.value,by=successes]
like image 165
Didzis Elferts Avatar answered Jan 03 '23 03:01

Didzis Elferts