2

I want to clean my R code, therefore i want to write several RScript's and call the Functions there, but i have no idea how to do this.

For example, I have the following call in my Main Class:

G = function(x) {
    return(-exp(-1i * x) * Conj(H(x+pi)) ) 
}

and the function H is written in an other R script as follows

H = function(x) {
    return (exp(-1i * x / 2) * cos(x / 2) )
}

Both RScripts are in the same Project but my Main Class doesen't recognize the function H.

Where is my error?

Thanks in anticipation

Matthias

3
  • 1
    Function G is dependent on function H. Did you define H before you defined G? Commented Apr 20, 2018 at 8:24
  • Hi, the code is working and the function H was defined before G, but now i want to exclude the function H in an other Rscript to clean my code, therefore it is not longer recognized. My qestion is not how to get access to a function in an other RScript. Commented Apr 20, 2018 at 8:27
  • How about rm(list=c("H"))? Wouldn't that remove H from your environment? Commented Apr 20, 2018 at 8:30

1 Answer 1

5

To call an RScript from another script, you need to source it at the beginning:

source("H.R")
# H is now available
G = function(x) {
     return(-exp(-1i * x) * Conj(H(x+pi)) ) 
}

If you want to clean up your functions, you can also build a package containing all your functions.

A little bit more of work, but definitely worth the effort!

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Colin FAY and thanks for your answer. I created a package already and in this package is my Main and the function H. I also added source("H.R") but i get the message: "cannot open file 'H.R': No such file or directory"
I found my error, i have to add the whole path. Thank you for your help.