Skip to content

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.

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 R
myString <- "Hello, World!"
# The print() function displays the object's value
print(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.

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.

  1. In RStudio, create a new script file (File > New File > R Script).
  2. Type your code into the script editor:
# My first program in R Programming
myString <- "Hello, World!"
print(myString)
  1. 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) or Cmd+Enter (macOS).
    • Run the entire script: Use the source() command in the console, e.g., source('my_script.R').

Running the script will produce the same output in the console:

[1] "Hello, World!"

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.

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.