dynamically creating functions in r
Hi,
On Wed, Oct 5, 2011 at 10:57 AM, honeyoak <honeyoak at gmail.com> wrote:
it is possible to dynamically create functions in R using lists? what I want to do is something like this: ? ? ?a = list() ? ? ?for (i in 1:10) a[[i]] = function(seed = i) runif(seed) so that when I call a[i] I get random draws 1,2,....i unfortunately R only uses the last i .
I'm not sure I understand what you want. Do you want to set a new seed for
the random number generator, or do you want a random vector of length i
each time?
If the former, I'm not sure why you'd want to do that, but your choice
of variable
names makes me wonder.
If the latter, you just need a bit of clean-up.
a <- list()
for (i in 1:10) {
a[[i]] <- runif(i)
}
But that's not dynamically creating a function, so maybe I'm missing the point.
I would also like to know if there is a run-all function without explicitly looping or using lapply. for example if I have a list 'b' of functions if I called ? ? ?run-all(b) all the functions in list 'b' would be run thanks.
What's wrong with lapply? I think we need to know more about what you're trying to do. You might also want to look at do.call(). Sarah
Sarah Goslee http://www.functionaldiversity.org