When you are in the RStudio window, you can open a script either by selecting File -> New File -> R Script
or with Ctrl+Shift+n
. From there you can put your function in there and run it. The function will only appear in your environment pane if you assign the function to a variable. So running:
function(x){
print(x)
}
will not save it to your global environment. If you assign it like this:
my_func <- function(x){
print(x)
}
and then run this code (either by clicking Run
or using the keyboard shortcut Ctrl+Enter
) then the function my_func
will appear in your global environment (i.e., in the environment tab).
If you want to source this function into multiple scripts but do not want to paste it into each script, then you can save the script with the function as something (e.g., my_function.R
) and then at the beginning of the script that uses the function you can call this:
source("path/to/my_function.R")
This will essentially run the entire code base from my_function.R
and everything created in it will now be in your global environment.
As a side note, try to avoid @jennybryan setting your computer on fire and check out this thread about best practices for sourcing files (in this case an R script) into other R scripts or markdown documents