Double FOR
I want to run through a formula several times with several different variables (which are defined by independent vectors of equal length 10 elements). It looks like this:
One way would be explicitly create your data first: df <- expand.grid(a = 1:5, b= 1:5, c=1:5) And then take advantage of vectorisation to compute DIC.hat: with(df, sum(-2*((log(1/sqrt(2*pi*a^2))*exp((((b-c)/a)^2)/-2)))) which looks awfully like differences of two normal densities, so you might be able to use dnorm (which might be faster as it is written purely in C (but not noticeably so unless you have a lot of data), but will make your algorithm more clear). By breaking it down into multiple steps, hopefully you can get a better idea of what's going on. Putting browser() in the middle of your loop would be another way for you to check out what is really happening. Hadley
On 11/26/05, Ginestet, Cedric <c.ginestet at imperial.ac.uk> wrote:
Hi,
function (m,s,y)
{
for (j in m){
for (k in s){
for (i in y){
DIC.hat<-sum(-2*((log(1/sqrt(2*pi*s^2))*exp((((y-m[j])/s)^2)/-2))))
}
}
}
DIC.hat
}
My problem is that R runs the three variables at the same time providing
me with 10 new elements for DIC.hat, when I would like to have 20 times
more.
Can you help?
----------------------------------------------------
Cedric Ginestet
Department of Epidemiology and Public Health
Faculty of Medicine
Imperial College
Norfolk Place
London
W2 1PG
UK
Tel: +44 (0)77 8688 4313
Fax: +44 (0)20 7402 2150
[[alternative HTML version deleted]]
______________________________________________ R-help at stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html