There are a few different file types that are associated with R. An “R script” is a text file with R commands, and has a “.R” extension. You can save all or some of the variables from a workspace into an “Rdata” file with a “.Rdata” extension, file example “lab2.Rdata”. More on this later.
But before even doing this, I'll introduce the “Project” feature that is particular to R studio. It is not a feature of R. A R Studio Project creates a new folder in which you can save all of your data, files and plots. R studio will remember all of this from session to session. If you close R Studio, and then open it back up, it will remember everything, even if you open it from a different computer.
To create a Project, from within R Studio, click Project -> Create Project. (You may be prompted whether you want to close your current R session… If you're just starting, there is no reason no to… if you have something important open, you may want to save it first). You will then be prompted whether you want to create a new folder, or to use an existing folder. This is up to you. Whatever you choose, R will then start up inside the project folder. You might create a folder called lab 2, for example. There will also be a file with the extension “.Rproj”- if you click on this from your file explorer, it will start up R Studio exactly where you left off.
Once you're in R Studio, create an R script. Type CTRL + SHIFT +N or go to File -> New -> R Script. It will create a blank script. This is like a text document, but everything is an R command (or a comment). Suppose your R script looks like this:
There are a few ways you can work with this. If you place your cursor on the first line, you can either click “Run”, or type CTRL + RETURN, and the line will be pasted to the Console and executed. You can select multiple lines and Run, and the entire selection will be run. You can Click Source (or type CTRL+SHIFT+S), and the entire script will be run silently. You can check that x now equals 2, but you will never know that it was first 3, or that x+3 was 6. If you Click Source -> Source with Echo (CTRL + SHIRT + RETURN), then everything will run, AND all of the results will be printed out to screen.
Here's my usual workflow:
Don't forget to save the script periodically. Your Project is saved automatically. I usually put my Projects in a Dropbox folder, that way I can run them from either my desktop or my laptop.
I love the Project feature of R Studio.