[R] Creating functions with a loop.

Rui Barradas ruipbarradas at sapo.pt
Wed May 23 14:59:02 CEST 2012


Hello,

To keep related objects of the same nature in the same structure makes 
very good sense but why not name the functions in the list after they 
were created?

Using 'NextFunc' of a previous post,


f.list <- list()
f.list[[1]] <- function(x) x^2
f.list[[2]] <- NextFunc(f, 1)
f.list[[3]] <- NextFunc(f2, 2)

names(f.list) <- paste("ff", 1:3, sep=".")

f.list[[ 3 ]](3) # 6 = 3^2 - 1 - 2
f.list[[ "ff.3" ]](3) # the same
f.list$ff.3(3) # the same


Hope this helps,

Rui Barradas
Em 23-05-2012 11:00, "R. Michael Weylandt" <michael.weylandt at gmail.com> 
escreveu:
> Date: Tue, 22 May 2012 18:50:08 -0400
> From: "R. Michael Weylandt"<michael.weylandt at gmail.com>
> To: Etienne Larriv?e-Hardy 	<etienne.larrivee-hardy.1 at ulaval.ca>
> Cc:r-help at r-project.org
> Subject: Re: [R] Creating functions with a loop.
> Message-ID:
> 	<CAAmySGMpyobjLP5qHRg3S6UM0C5T08Yn-CUiUg9eQ2SSTobLpw at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
>
> You can do what you want with the get() and assign() functions, though
> it might be easier and better to use match.fun() than get()
>
> Much better though would be to build your functions in a list and call
> the n-th element of the list with syntax like
>
> f.list[[3]](4)
>
> will call the function in the third element of the list with argument 4.
>
> Best,
> Michael
>
> On Tue, May 22, 2012 at 1:24 PM, Etienne Larriv?e-Hardy
> <etienne.larrivee-hardy.1 at ulaval.ca>  wrote:
>> >  Michael's method seems to be working but I still can't get to wrap it in a
>> >  loop since I cannot get the loop to dynamically change the functions' name,
>> >  i.e. ff1, ff2, ff3, ... In other words, I would need the first iteration to
>> >  create the function ff1, the second to create the function ff2, ...
>> >  Furthermore, does anyone know of a way to call said functions from a loop in
>> >  a way that the first step of the loop calls ff1, the second calls ff2 and so
>> >  on?
>> >
>> >  The 2 problems should be closely related I think.
>> >
>> >  Thanks for the time
>> >
>> >  --
>> >  View this message in context:http://r.789695.n4.nabble.com/Creating-functions-with-a-loop-tp4630896p4630938.html
>> >  Sent from the R help mailing list archive at Nabble.com.
>> >



More information about the R-help mailing list