Running Your First R Script
Join our community on Telegram!
Join the biggest community of Pharma students and professionals.
Now that you are familiar with the RStudio interface, the next step is to write and execute code. In R, you can run commands directly in the Console for quick results, or write them inside a Script file for reproducibility and long-term use.
1. Script vs. Console: When to Use Each
Understanding where to write your code is an important part of professional programming. The Console is meant for quick, temporary work. Any commands typed there are executed immediately when you press Enter, but they are not saved once RStudio is closed. This makes the Console ideal for quick calculations, testing a single command, or exploring data interactively. However, it becomes difficult to edit or reuse previous commands.
A Script file, which has a .R extension, is designed for permanent and structured work. Code written in a script is saved and can be reused, edited, or shared later. It only runs when you choose to execute it, giving you better control. Script files are best for building projects, performing analyses, and maintaining clean, professional code.
2. Creating Your First Script
To create your first R script, go to the top menu in RStudio and select File > New File > R Script. A new blank tab will appear in the Source pane. Type the following example into the script:
# My First R Script
message <- "Hello, R World!"
print(message)
# Simple Math
result <- 5 + 5
print(result)
3. Console Output
[1] "Hello, R World!"
[1] 10
4. Executing the Code
There are several ways to run the code in your script. The most common method is the keyboard shortcut. Place your cursor on the line you want to run and press Ctrl + Enter on Windows or Cmd + Enter on macOS. You can also click the Run button at the top-right of the Source pane to execute the selected line or block of code. If you want to run the entire script at once, highlight all the code and click Source to execute the whole file.
5. Best Practices for Writing Scripts
To keep your code clean and professional, always use comments to explain your logic by placing the # symbol before any note. Use the assignment operator <- when assigning values to variables, as this is the standard convention in R. Choose clear and descriptive variable names, such as student_score instead of single letters. Finally, save your script frequently with a .R extension so it can be reused later.
