[R] import function without overwriting function with the same name
William Dunlap
wdunlap at tibco.com
Sat Aug 3 23:35:21 CEST 2013
Here is an example of making a list of environments, each containing
a function called 'f' that was defined in an R script file.
First I make examples of the sort of files I think you are thinking of;
each defines 'f'. The file names are in the character vector 'tfs'.
> tfs <- vapply(1:3, function(i){ tf <- tempfile(); cat("f <- function(x)x +", i, "\n", file=tf) ; tf}, FUN.VAL="")
> readLines(tfs[2]) # the 2nd file
[1] "f <- function(x)x + 2 "
Now parse and evaluate each file in its own environment:
> funEnvs <- lapply(tfs, function(file) { envir <- new.env() ; eval(parse(file), envir=envir) ; envir })
Now try using 'f' that was defined in the 2nd file:
> funEnvs[[2]]$f(100)
[1] 102
Now try using all of the 'f's:
> vapply(funEnvs, function(envir) envir$f(100), FUN.VAL=0)
[1] 101 102 103
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Martin Batholdy
> Sent: Saturday, August 03, 2013 2:05 PM
> To: r-help at r-project.org
> Subject: Re: [R] import function without overwriting function with the same name
>
> > env.lst <- lapply(1:5, new.env)
> >
> > seems to work just fine
>
> ok, as far as I understand I would create 5 new environments by this.
> But how do I access and change the environment?
> What is the name of the environment?
>
>
> Here is a more concrete example and the general problem:
>
> source('functions1.R')
> source('functions2.R')
>
> now functions1.R and functions2.R contain function definitions with the same function-
> names.
> So as soon as I execute source('functions2.R'), I overwrite the function definitions
> already imported by source('functions1.R').
>
> How can I avoid this?
> ______________________________________________
> 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