Saving your code

Filed under: R data-science

Last updated on: July 12, 2021

Length:
3 minute read, 506 words

Using scripts

So far, we have typed commands into the console. But you will notice that there is no option to save the code that we have typed into the console. Most projects would require files that can be saved so that we can work on them over a period of time and execute them a multiple times without having to type them out each time.

We can do this by placing code inside a file. There are many different types of files but, for now let’s start with a simple R script.

So far, we have typed commands into the console. But you will notice that there is no option to save the code that we have typed into the console. Most projects would require files that can be saved so that we can work on them over a period of time and execute them a multiple times without having to type them out each time.

We can do this by placing code inside a file. There are many different types of files but, for now let’s start with a simple R script.

Now we need to get all the commands that we tried out earlier into this script. One option would be retype all the commands but that is an extremely tedious way of doing this. Instead, we can access all the previously executed code using the history tab as shown below and copy it over to the source file.

We don’t need the line that generated the error, so let’s remove that and save the file. I am calling it my_first_script. But you can call it anything you want.

The files tab in RStudio shows all your files and folders. Navigate to the folder you saved the script in to check if it is actually there.

Execute code using a script

Once you have saved your file, you can run it as many times you would like without having to retype any of the commands. There are two ways you can do this. The first is by stepping through the script one line at a time using the run button.

The second is by running the full script by sourcing the file. You can do this by clicking on the source button. Notice that the source command generates a new line in the history tab. This is the command that is used to source a file. Now we can close the script and paste this command from the history tab using the To console button and run it to execute all of the code within that script as shown below. Also notice how I use the broom 🧹 icon to clear the code in the console before sourcing the script.

RStudio look and feel

RStudio comes with tons of options to customize how it looks and feels. You can customize the different tabs, choose a different font, apply a darker theme etc. I personally like a dark theme, so I am going to switch over to that for the rest of this book.