0

I have these two R scripts which will be sourced in same R instance.

Script 1:

fun1 <- function(x, y)
{
  ret = x+y+mean(x,y)
  return(ret)
}

fun2 <- function(x, y, z)
{
  k = fun1(x, y)
  print(x+y+k)
}

I want script 2 to be like this

fun3 <- function(k, l)
{
  k = fun4(k, l)
  m = k / sd(k,l)
  return(m)
}

fun4 <- function(k, l)
{
  ret = k+l+mean(k,l)
  return(ret)
}

But what people write is

fun3 <- function(k, l)
{
  k = fun1(k, l)
  m = k / sd(k,l)
  return(m)
}

But I dont want to allow functions in script 1 to be called from script 2. How can I do this?

I know I can do this in script 1 but there are many functions like fun2 and some of them are huge, so this is not possible for me

fun2 <- function(x, y, z)
{
  fun1 <- function(x, y)
  {
  ret = x+y+mean(x,y)
  return(ret)
  }
k = fun1(x, y)
print(x+y+k)
}

I know about creating new environments, but I am not sure will that help.

Sim101011
  • 305
  • 1
  • 13
  • 1
    Can I ask why? `fun3` explicitly calls `fun1` from script 1. Do you want to call a different `fun1` that is not the one from script 1? – Maurits Evers Oct 06 '16 at 12:00
  • 1
    Where do functions for `script 2` come from, then? Perhaps you could do some smart `source`ing? – Roman Luštrik Oct 06 '16 at 12:04
  • @MauritsEvers Thats I want to avoid, I don't want to allow anyone to call function not in their script. I want that script 2 to have its own function fun4 doing same thing as fun1. – Sim101011 Oct 06 '16 at 12:21
  • @RomanLuštrik : These two scripts are going to be written by two different persons. – Sim101011 Oct 06 '16 at 12:22
  • I don't understand. `fun3` seems to call `fun1`, which -- unless you re-define it elsewhere -- is defined in script 1. So either give the function called from within `fun3` a different name, or introduce a sensible conditions within `fun3`. I'm afraid I can't say much more without a minex. – Maurits Evers Oct 06 '16 at 12:27
  • Can you elaborate more on your use case? Why do you think sourcing the functions in separate environments won't help? See e.g. http://stackoverflow.com/a/13092757/6455166, in the *Alternative using sys.source* section. – Weihuang Wong Oct 06 '16 at 12:32
  • @MauritsEvers I'm guessing what OP is after is that person writing script2 gets a warning "fun1 does not exist" if the person has not created themselves – Cath Oct 06 '16 at 12:32

2 Answers2

1

You could use ?environments for this. See also another similar question

env1 <- new.env()
env2 <- new.env()

assign("myfun", value = function(x) {
  mean(x)
}, envir = env1)

assign("myfun", value = function(x) {
  mean(x^2)
}, envir = env2)

myx <- 1:10

with(env1, myfun(myx)) # 5.5
with(env2, myfun(myx)) # 38.5

Basically, every single skript is gonna be run in its own environment. Is this what you are trying to achieve ?

Community
  • 1
  • 1
Drey
  • 3,314
  • 2
  • 21
  • 26
1

At the end of each script just delete the functions defined in them.