-----Original Message-----
From: r-help-bounces at r-project.org
[mailto:r-help-bounces at r-project.org] On Behalf Of bsm2
Sent: 23 January 2013 20:00
To: r-help at r-project.org
Subject: [R] Pasting a list of parameters into a function
I need to repeat a function many times, with differing
parameters held constant across iterations. To accomplish
this, I would like to create a list (or vector) of
parameters, and then insert that list into the function.
For example:
q<-("l,a,b,s")
This isn't a ist, it's a single quoted string. A list would be
q <- list(l=<value>,a=<value>, b=<value>, s=<value> )
(with common sense replacement of <value> with the values you want to pass
genericfunction<-function(q){
}
That'll work, assuming your function dereferences q, for example using q$l or, perhaps, using with()
Other things might work too though. For example, assuming each item is single-valued numeric, set up a matrix with columns l, a, b, s or or data frame (say d) with variables l, a, b, s, then use
apply(d, 1, genericfunction) #iterate over rows, coercing each row to vector
with g using either the numeric indices (like q[1], q[2]) or, for the data frame version, the names (q['a'] etc) because in the data frame version q will be a named vector.
You could also construct a list of lists, and use lapply or sapply to do the iteration over the whole list; that would work whatever type l, a, b, s are. Example:
param.sets <- list(
list(l=1,a='a', b=2.3, s=TRUE ),
list(l=5,a='p', b=7.5, s=FALSE ),
list(l=3,a='r', b=2.5, s=TRUE )
)
a.function <- function(q) with(q, paste(l, a, b, s) )
sapply(param.sets, a.function)
You could also use mapply and supply l, a etc as individual vectors, factors etc, but that would need a different function definition:
d <- data.frame(l=1:6, a=gl(3,2, labels=letters[1:3]), b=6:1, s=rnorm(6)) #to package them neatly
mfun <- function(l, a, b, s) paste(l, a, b, s)
#Then
with(d, mapply(mfun, l, a, b, s))
*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}