-1

I am looking for a technique that combines the following two questions:

Define all functions in one .R file, call them from another .R file. How, if possible?

The R equivalent of Python from x import y as z

In other words, I want to import a specific function from someone else's .r file. Under a different name.

Community
  • 1
  • 1
Vorac
  • 8,726
  • 11
  • 58
  • 101
  • @musefan how can my question be made clearer? – Vorac May 30 '18 at 10:02
  • Well you could write one for starters... you haven't put anything. You can't just link 2 questions and that's it. Your question needs to be able to stand on it's own, not rely on links – musefan May 30 '18 at 10:50

3 Answers3

1

You can use source as follows:

In test.R script:

test <- function() message("Hello")

Then, source that file using

someone <- new.env()
source("test.R", someone)

To call someone's code, use

someone$test()

If possible, ask that someone to write a R package.

chinsoon12
  • 25,005
  • 4
  • 25
  • 35
1

We call source with local=TRUE inside a new function, and return only the needed function:

source1 <- function(path,fun){
  source(path, local= TRUE)
  get(fun)
}

from x import y as z will be written:

z <- source1(x,y) # where y is a string

Example:

# create 'test.R' file in working directory
write("test  <- function(a,b) a + b
      test2 <- function(a,b) a - b",
      "test.R")

new_fun <- source1("test.R","test2")

new_fun
# function(a,b) a - b
# <environment: 0x0000000014873f08>

test
# Error: object 'test' not found

test2
# Error: object 'test2' not found

# clean up
unlink("test.R")
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167
  • 1
    How awesome is that?! I still can't get used to how things by default are global and mutable. – Vorac May 30 '18 at 12:04
0

AFAIK there is no such mechanism in R.

Of course you can do

x.R y <- function() {do_something}

z.R source("x.R") z <- y rm(y)

A better options would be to make x.R into a package. Then you simple do z <- x::y

The best solution is to convert both x.R and z.R into packages and use @importFrom x y into package z and don't bother with changing the name of the function.

Thierry
  • 18,049
  • 5
  • 48
  • 66