[R] Creating functions with a loop.
R. Michael Weylandt
michael.weylandt at gmail.com
Tue May 22 17:34:20 CEST 2012
Interpreting your question slightly differently, where ff.k(x) is a
function call.
Suppose you want to get a list of functions like
x^2
x^2 -1
x^2 - 3
x^2 - 6
It's perfectly possible with something like this:
NextFunc <- function(f, i) {
# Takes in a function f and returns
# a different function that gives you
# f(x) - i
force(i) # probably unnecessary, but good practice as this just
might bite you in a loop
function(x) f(x) - i
}
Then
f <- function(x) x^2
f2 <- NextFunc(f, 1)
f3 <- NextFunc(f2, 2)
f3(3) # 6 = 3^2 - 1 - 2
Which should be wrappable in a loop.
Michael
On Tue, May 22, 2012 at 11:08 AM, David Winsemius
<dwinsemius at comcast.net> wrote:
>
> On May 22, 2012, at 10:06 AM, Etienne Larrivée-Hardy wrote:
>
>> Hi
>>
>> I am trying to create n functions where each function is defined in
>> function one step before, i.e. something like
>>
>> ff.k(x) = ff.j(x) - sum(1:j), for j=k-1
>
>
> There is a cumsum function:
>
>> cumsum(1:10)
> [1] 1 3 6 10 15 21 28 36 45 55
>
> Did you mean something like?:
>
> ff.k[j] <- ff.j[j] - sum(1:j), for j=k-1
>
> In R the paren, "(", indicates that you are calling a function whereas you
> appear interested in making an indexed assignment to a vector.
>
>
>>
>> Is it possible? If it isn't and I manually create each function then is
>> their a way to call them through a loop? My objective is to calculate
>> something like
>>
>> result.k = ff.k(x1)/ff.k(x2) for k in 2:n
>
>
> You may have clear idea about which k-indices should go where in that
> expression, but I surely do not. What are 'x1' and 'x2'?
>
> --
>
> David Winsemius, MD
> West Hartford, CT
>
>
> ______________________________________________
> 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