R-beta: is there a way to get rid of loop?
Bill Simpson
wsimpson at uwinnipeg.ca
Fri Feb 27 18:14:11 CET 1998
Here is a programming question. The code I am using is quite slow and I
was wondering if there is a way to get rid of the for loop.
I am dealing with "interaction" in 2x2 table, and am using Edwards's G_I
(Likelihood, p. 194).
I label the cells in the table as follows
stim response
"y" "n" total
--------------------------------
y hit miss nsignal
--------------------------------
n false correct nnoise
alarm rejection
---------------------------------
Gsens<-function(nhit,nmiss,nfa,ncr)
{
# Edwards's G_I, measure of interaction, is measure of sensitivity
(xlogx(nhit)+xlogx(nmiss)+xlogx(nfa)+xlogx(ncr))-(xlogx(nhit+nmiss)+xlogx(nfa+ncr))-(xlogx(nhit+nfa)+xlogx(nmiss+ncr))+xlogx(nhit+nmiss+nfa+ncr)
}
BTW I can't figure out how to break the line at 80 cols. I tried \
but it didn't work (error message).
The question is about this function. It calculates 95% CI based on Monte
Carlo simulation. [Edwards gives no ref on the sampling distrib of G_I]
The number of signal trials is binomial random
variable with p=.5, so it is simulated that way. This is fine, I can get
a vector of 2000 ns numbers that way. However, for each ns I want an
associated binomial variate with p=phit. Is there a better way to do this
than by looping?
Gsens.ci.mc<-function(nhit,nmiss,nfa,ncr)
{
#monte carlo simulated 95% CI
nsignal<-nhit+nmiss
nnoise<-nfa+ncr
phit<-nhit/nsignal
pfa<-nfa/nnoise
ns<-rbinom(2000,nsignal,.5)
nn<-nsignal+nnoise-ns
nh<-NULL
nf<-NULL
for(i in 1:2000)
{
nh<-c(nh,rbinom(1,ns[i],phit))
nf<-c(nf,rbinom(1,nn[i],pfa))
}
g<-Gsens(nh,ns-nh,nf,nn-nf)
quantile(g,c(.025,.975), na.rm=TRUE)
}
Thanks very much for any help!
Bill Simpson
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list