R - Basic Syntax
R - Basic Syntax
Section titled “R - Basic Syntax”Let’s begin our journey into R programming with the classic “Hello, World!” program. You can interact with R in two primary ways: directly in the R console for quick commands, or by writing and running scripts for more complex tasks. The modern workflow heavily relies on using a script editor within an IDE like RStudio.
Working Interactively in the R Console
Section titled “Working Interactively in the R Console”Once R is installed, you can start the R console. In RStudio, the console is one of the main panes. You’ll see a > prompt, where you can type commands and get immediate feedback.
# The '<-' is the assignment operator in RmyString <- "Hello, World!"
# The print() function displays the object's valueprint(myString)Executing this code in the console will produce:
[1] "Hello, World!"Pro Tip: In an interactive session, you can often just type the variable name to have its value printed automatically, so myString would have produced the same output.
Using R Script Files in RStudio
Section titled “Using R Script Files in RStudio”For any task that involves more than a few lines of code, you should use an R script file (with a .R extension). This allows you to save, edit, and re-run your work, which is essential for reproducibility.
- In RStudio, create a new script file (
File > New File > R Script). - Type your code into the script editor:
# My first program in R ProgrammingmyString <- "Hello, World!"
print(myString)- Execute the code. You have several options in RStudio:
- Run the current line or selection: Place your cursor on a line and press
Ctrl+Enter(Windows/Linux) orCmd+Enter(macOS). - Run the entire script: Use the
source()command in the console, e.g.,source('my_script.R').
- Run the current line or selection: Place your cursor on a line and press
Running the script will produce the same output in the console:
[1] "Hello, World!"Comments in R
Section titled “Comments in R”Comments are crucial for making your code understandable to others and to your future self. In R, anything following a hash symbol (#) on the same line is considered a comment and is ignored by the interpreter.
# This entire line is a comment.x <- 10 # This is an inline comment explaining the variable.Multi-line Comments
Section titled “Multi-line Comments”R does not have a formal syntax for multi-line or block comments. The standard practice is to simply begin each line of the block with a #.
# This is the first line of a multi-line comment.# This is the second line. It explains a complex# function that will be defined below.Best Practice: Modern IDEs like RStudio provide a keyboard shortcut (typically Ctrl+Shift+C or Cmd+Shift+C) to comment or uncomment a selected block of code, making this process effortless.