Scripts vs. code (newbie question)

Coming to Rstudio from plain R, I'm very confused about text scripts vs. code, which is coming up in the context of debugging. If I double click on a function in the enivronment list, it calls view(foo) and opens it for viewing, but not editing. However, if I want to edit it, apparently I need to open a script (text) file (or create one by cut-and-paste). I can run it using the little run button. But how do I turn it into an R function? It still does not show up in my environment list. How does "source" fit into this?

Finally, how do I then link the script with the R function for debugging purposes? I can make this work by using edit(foo) or fix(foo) in the traditional R fashion, but then I am editing in an editor window.
Obviously I'm very confused. Thanks!


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:


will not save it to your global environment. If you assign it like this:

my_func <- function(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:


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

1 Like

Thanks. I will check out the pointed to thread.

If it's not too obvious a suggestion, you could go through the 'Essentials' tutorials here:

1 Like

Thanks for the pointer; will do.