The Script Window is the place to enter and run your code so that it is easily edited and saved for future use. Usually the Script Window is shown at the top left in RStudio. If this window is not shown, it will be visible when you open a previously saved R script, or when you create a new R Script.
To execute your code in the R script, you can move your cursor anywhere in the line of the code, and either click on Run or press Cmd/CTRL + Enter on your keyboard.
To execute your code in the Console Window, you can enter code directly and hit Enter. The commands that you run will be shown in the History Window on the top right of RStudio. You can save these commands for future use, yet this is not recommended for documenting your code.
Comments in R are preceded by the # symbol; anything following this symbol will not be executed. However, writing comments in your code is important for documentation purposes.
2.2 Saving and Opening R Script Files
Saving an R Script: To save your work in R, you create what is known as an R script. This is a plain text file containing the code you’ve written, which can be run in R to perform tasks like data analysis, visualization, etc. Here’s how to save an R script:
Click on File > New File > R Script in the RStudio menu bar.
Write your code in the R script window.
Click on File > Save As in the RStudio menu bar.
Choose a location on your computer to save the file, and give it a name ending in .R (e.g., myscript.R).
Click Save.
Opening an R Script: To open an existing R script for editing or execution, follow these steps:
Click on File > Open File in the RStudio menu bar.
Navigate to the location of the R script file on your computer.
Click Open.
2.3 Exercise B
Q1
Create a new R script in RStudio and save it as myfirstscript.R.
Write a code that prints Hello World in the R script and run the code.