[R] (not so real) function (more like #include)
Meinhard Ploner
meinhardploner at gmx.net
Thu Oct 5 11:53:31 CEST 2006
Thanks a lot! longfun2 & longfun3 work perfect for my "very
untypical" problem. As I have many local variables, usual functions
with parameters are very uncomfortable, but the code you gave me is
great!
Meinhard
On Oct 4, 2006, at 5:25 PM, Gabor Grothendieck wrote:
> longfun could just pass a, b and d to each of the individual
> functions and each of the individual functions could pass
> out back as a return value.
>
> f1 <- f2 <- function(a, b, d) a+b+d
>
> longfun1 <- function() {
> a <- b <- d <- 1
> out <- f1(a, b, d)
> out <- f2(a, b, d) + out
> out
> }
>
> longfun1() # 6
>
> If the problem is that a, b and d actually represent 100 variables,
> say,
> and its a nuisance to pass them all explicitly you could do this:
>
> f1 <- f2 <- function() with(parent.frame(), a + b + d)
>
> longfun2 <- function() {
> a <- b <- d <- 1
> out <- f1()
> out <- f2() + out
> out
> }
>
> longfun2() # 6
>
>
> or you could do it this way if you would prefer to have longfun
> control the scoping rather than having it done within each
> individual function:
>
>
> f1 <- f2 <- function() a+b+d
>
> longfun3 <- function() {
> a <- b <- d <- 1
> environment(f1) <- environment(f2) <- environment()
> out <- f1()
> f2() + out
> }
>
> longfun3() # 6
>
>
> On 10/4/06, Meinhard Ploner <meinhardploner at gmx.net> wrote:
>> Hello R users,
>>
>> I have a very long function with parts of that looking like a list of
>> jobs. The first part of the function defines a lot of local
>> variables, which are used by the jobs. Now I extracted the "job" part
>> und putted them into an external file, used by "source(, local=T)",
>> which is more comfortable to me. Apart from that it gives me the
>> opportunity that more users can work on the project. Is it possible
>> to define a function for that code and passing to it the environment
>> of f() without save(list=ls()) and load() .... ?
>>
>> Thanks in advance
>> Meinhard Ploner
>>
>> longfun <- f() {
>>
>> ## lot of local variables:
>> a <- ...
>> b <- ...
>> d <- ...
>> ...
>>
>> out <- ...
>>
>> source("job1.txt", local=TRUE) #changes out, uses a, b,
>> d, ...
>>
>> source("job2.txt", local=TRUE) # changes out, uses a, b,
>> d, ...
>> ...
>> }
>>
>>
>>
>> version
>> _
>> platform i386-apple-darwin8.6.1
>> arch i386
>> os darwin8.6.1
>> system i386, darwin8.6.1
>> status
>> major 2
>> minor 3.1
>> year 2006
>> month 06
>> day 01
>> svn rev 38247
>> language R
>> version.string Version 2.3.1 (2006-06-01)
>>
>> ______________________________________________
>> R-help at stat.math.ethz.ch 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