[R] Pasting a list of parameters into a function

S Ellison S.Ellison at LGCGroup.com
Fri Jan 25 16:06:56 CET 2013

> -----Original Message-----
> I'd love to write a code that would allow me replace the example code:
> fit1F <- mle2(LL, fixed=list(xhalf=6))
> with something like:
> var<-xhalf
> val<-6
> fit1F <- mle2(LL, fixed=list(var=val))
> or
> var<-c("xhalf","=")
> val<-6
> fit1F <- mle2(LL, fixed=list(var,val))
> Replacing the value in question is easy enough, but I can't 
> figure out exactly how to replace the identity of the 
> variable that will be held constant.

I'm not sure exactly _where_ in the code you need to replace things.

If it's at the time you call your code (presumably a function) manually, the answer's kind of obvious; write a function that takes a 'fixed' argument and pass that directly to mle2.

If you want to cycle through a set of fixed values, though, you could probably do that by starting with the complete list and then cyclyng through it. A very simple example might look like this:

show.fixed <- function(i, l, a, b, s, fixed) {
	#A simple function that takes a 'fixed' parameter in the same format as mle2's 'fixed'; 

	cat(paste(i, ":", l, a, b, s, "with", names(fixed), "fixed at", fixed[[1]], "\n"))
		#This function just prints out the values provided 
                                #followed by the name and fixed value of the 'fixed' element

#To pass different things to such a function:

#i) Set up a complete list of parameters with their fixed values
fixed.scope <- list(l=1, a=3, b=5, s=23)
	#This could be your starting parameter set if that's convenient

#ii) reference elements of the list inside a loop
#     I've out such a loop inside the following function:

f <- function(l=0, a=1, b=2, s=3, fs) {
	#fs is our complete set of possible fixed values
	for(i in 1:4) {
		show.fixed(i, l, a, b, s, fixed=fs[i])	 #you would have mle2 called here instead of show.fixed
			# fs[i] sends the i'th element of fs to the function as a one-element list 	with the right name

# iii) call the function with the 'fixed scope' list
        #shows that setting fixed=fs[i] provides the function with the (named) i'th element of the list of fixed parameters

Clearly* you could update the values actually held in fs at each cycle if what you wanted to do was optimise three parameters for different values of each fixed element, or (somewhat dodgy, but I've had to resort to such things with ill-behaved optimisations) do 'three at a time' optimisation to sneak up on a maximum. 
You could also build fs inside your function instead of supplying it from outside.

Steve Ellison

*'clearly' in the usual mathematical sense of "after several years of study and considerable thought one might see that..."

This email and any attachments are confidential. Any use...{{dropped:8}}

More information about the R-help mailing list