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:
- It's part of a "core" package and loaded whenever you start R (e.g.,
sum).
- You load the package containing the function in the script. (e.g.,
library(survival) lets you use the Surv function).
- You define the function in the script (e.g.,
my_fun <- function() ...).
- 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.