New function not seen by R sourcing command


#1

Hi there,
I'm a brand new user (less than 2 weeks) both for R & R-Studio .
It goes quite smoothly but yesterday must have made a mistake in R-Studio.
When I'm creating new functions in the active script, if I source it I have always the message like this one:
Error in EvaluateFEFFIndicators(FEFFList) :
could not find function "EvaluateFEFFIndicators"
The new function is also not proposed in the "completion" window as the old I have already done.
What is the problem?
I have looked to what is seen by R using the search command, and it looks not bad.
I don't know if there is a link but I have used the "Clear objects from the workspace" button (paintbrush).
Is there somebody who knows what to do?
Thanks in advance.


#2

Are you loading the necessary packages with library(package) (replacing "package" by the package name of course).


#3

For simplicity, let's assume you're running the script in a fresh session of R with no changes to the default options that might affect the result (which is the best way to run a script).

There are four basic ways to get a function into the script's environment:

  1. It's part of a "core" package and loaded whenever you start R (e.g., sum).
  2. You load the package containing the function in the script. (e.g., library(survival) lets you use the Surv function).
  3. You define the function in the script (e.g., my_fun <- function() ...).
  4. You source() another script which defines the function (e.g., source("path/to/fun_defs.R")).

Basically, the only guaranteed way to make sure you have what you need is to explicitly have the script bring it in (except for the first way). To see if your script can run in a clean environment, just restart your session (in R Studio, Ctrl + Shift + F10) and run it.

If you created the function in the console instead of a script, then you might be able to retrieve it from the command history. Just use the command history() to view it.


#4

A fifth way is to use package::function() (not sure about getting it into the script environment though. But it is a fifth way to use the function).


#5

A sixth way is getExportedValue("survival", "Surv"). And if we include all ways using namespace and environment tricks, we're probably pushing two dozen ways. But anyone who uses the paths beyond your fifth in their code is asking for trouble.


#6

Sorry, was off yesterday.
Now it works again, I see the new functions that I'm writing in the R-Studio editor when I launch the source command.
Thanks very much for your help.
I'm afraid that I might have new questions in the future when I discover more functionalities....