[R] foreach loop - rejection method

joris meys jorismeys at gmail.com
Thu Oct 8 14:13:28 CEST 2009

First, you should define your function as :

test <- function(cand2,phi,lambda,
whatever-arguments-you-want-to-use-further){... insert code here ...}
All variables you use inside a function only exist within that
function. Your parameters/arguments is the interface between the
function and the outside world.

Then you can refer to it as :

In any case, if you use a function there is hardly any need to use
foreach(). With a correctly defined function, I'd use lapply()

Kind regards

On Thu, Oct 8, 2009 at 2:56 AM, dunno87 <benparker1987 at hotmail.com> wrote:
> Hi Everybody,
> Thanks in advance for your help.
> This is my first time using the foreach statement and I cant get it to work
> properly so here is what i have
> test<-function(){
> repeat {
> cand2[l-1]<-rinvgamma(1,phi,lambda[l-1])
> q2<-dinvgamma(cand2[l-1],phi,lambda[l-1])
> p2<-cand2[l-1]^-1.5*exp(-y[l]^2/(2*cand2[l-1]))*exp(-((log(cand2[l-1])-mu_t_cand[l-1])^2)/2*sigmasq)
> ratio<-p2/(c[l-1]*q2)
> if (runif(1)< ratio) {break}
> }
> f2[l-1]<-min(p2,c[l-1]*q2)
> }}
> foreach(l=2:(n-1),.combine=c,.packages='MCMCpack',.options.nws=li
> st(chunkSize=250)) %dopar% test()
> even though i've created the array earlier called cand2 when i run this code
> i get the error object "cand2" not found.
> What I'm trying to do is the rejection method for my cand2. i need cand2 and
> f2 as vectors as output both of length l-2 in the correct order.
> if i do a for loop as normal it works perfectly. Any ideas?
> Ben
> --
> View this message in context: http://www.nabble.com/foreach-loop---rejection-method-tp25796927p25796927.html
> Sent from the R help mailing list archive at Nabble.com.
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list