4 Scripts

Ok, let’s take a break before all the theoretical chapters to discuss about scripts.
I always say this word when talking to you about my job, but what are they? A script is essentially an ordered list of commands, used to not have to write again and again the same commands on the console. It can contain everything you type in the console, like functions, operations and even comments; in this way, you can do an analysis and store it as a “text” file that you can use as reference (so you know what you have done), use for another analysis, edit, share with others…
You will always write code in scripts, for all these reasons.

Let’s see how to create a script, write some code in it and run part of the script or even a small part of it in RStudio.

In the video we see a series of actions:

  1. To create a script, click the button on top left, then select “R Script” (or File -> New File -> R Script)
  2. Start writing the commands (even comments)
  3. To run a single line click “Run”
  4. To run the whole script (R starts from the beginning) click “Source”)

Suggetion: Comment, comment, comment everything. I know it is time consuming, but you will be so happy and greatful to read comments that help you understand what you’ve done months (or weeks) before.

Save

To save a script “File -> Save” or the usual shortcut “Ctrl-S” (Windows) or “Cmd-S” (MacOS). Use them for all the exercise from now on!

Source a script

Source a script from the console instead of having to open it and source from RStudio is very useful when you want to save time and create re-usable pipelines or analysis. Sourcing a script means to execute all the line of codes in that script. It can be archieved by doing source("path_to_file").

Now, head to the next chapter in which we will talk about numbers.