</>
Skip to content
R lessons (4/41)

R — Syntax

Assignment

R uses <- for assignment (read "gets"):

x <- 5
name <- "Ada"
is_active <- TRUE

You can also use =, but <- is the community standard. The <- operator reads naturally: "x gets the value 5."

x = 5      # works, but not R style
x <- 5     # preferred
x -> 5     # also valid, but rare and confusing

Comments

# This is a comment

x <- 5  # inline comment

# R has no multi-line comment syntax
# Use multiple hash lines for long explanations
# like this

R doesn't have block comments. For documentation, use roxygen comments (covered later).

Functions

Call functions with parentheses:

# Built-in functions
sqrt(16)          # 4
round(3.14159, 2) # 3.14
seq(1, 10)        # 1 2 3 4 5 6 7 8 9 10
c(1, 2, 3)        # combine values into a vector

The c() function is R's most fundamental — it combines values into vectors.

Named arguments

Many R functions use named arguments for clarity:

# position and name arguments
mean(c(1, 2, 3, 4, 5))         # 3
mean(c(1, 2, NA, 4, 5), na.rm = TRUE)  # 3

# Arguments can go in any order when named
paste("Hello", "World")               # "Hello World"
paste(sep = "-", "Hello", "World")    # "Hello-World"

Named arguments make code readable. Use them when the intent isn't obvious from position.

The pipe operator

The pipe %>% (from magrittr, built into dplyr) chains operations:

library(dplyr)

# Without pipe
result <- arrange(filter(mtcars, cyl == 6), desc(mpg))

# With pipe — reads left to right
result <- mtcars %>%
  filter(cyl == 6) %>%
  arrange(desc(mpg))

The pipe takes the result of the left side and passes it as the first argument to the right side. Code reads like a pipeline of transformations.

Tidy evaluation

R functions can accept column names without quotes — this is tidy evaluation:

library(dplyr)

mtcars %>%
  filter(cyl == 6) %>%    # cyl refers to the column, not a variable
  select(mpg, hp)          # same here

This is unique to R and makes data manipulation read like natural language.

R is vectorized

Most R operations work element-wise on vectors automatically:

x <- c(1, 2, 3, 4, 5)

x + 10       # 11 12 13 14 15
x * 2        # 2 4 6 8 10
x^2          # 1 4 9 16 25
sqrt(x)      # 1.00 1.41 1.73 2.00 2.24

No loops needed for element-wise operations. This vectorized approach makes R code concise and fast.

Multiple assignment

# Assign the same value to multiple variables
a <- b <- c <- 0

# Assign different values
x <- 1
y <- 2
z <- 3

Semicolons

R doesn't require semicolons, but you can use them:

x <- 5; y <- 10; z <- x + y

One statement per line is the convention. Semicolons are for rare cases where you want multiple statements on one line.

Line continuation

R continues lines when the expression is incomplete:

# R knows the expression isn't finished
result <- 1 + 2 + 3 +
  4 + 5 + 6

# Parentheses also allow continuation
result <- (1 + 2 + 3 +
  4 + 5 + 6)

Curly braces

Group multiple statements into blocks:

if (x > 0) {
  print("positive")
  print("number")
}

Single-statement blocks can omit braces, but always use them for clarity.

TRUE, FALSE, and NULL

TRUE    # logical true (also T, but use TRUE)
FALSE   # logical false (also F, but use FALSE)
NULL    # absence of a value
NA      # missing value
NaN     # not a number
Inf     # infinity

NULL means "nothing" — an empty object. NA means "missing" — data that exists but is unknown. They're different concepts.

Case sensitivity

R is case-sensitive:

x <- 5
X <- 10
# x and X are different variables

Function names are also case-sensitive: mean() ≠ Mean().

Common gotchas

Indexing starts at 1

x <- c(10, 20, 30)
x[1]   # 10 (not 20!)
x[0]   # numeric(0) — empty, not 10

R uses 1-based indexing, unlike Python and most other languages.

Assignment vs comparison

x <- 5    # assignment
x == 5    # comparison

# In if statements, use ==
if (x == 5) {
  print("equal")
}

Missing values propagate

c(1, 2, NA, 4) + 10
# 11 12 NA 14  — NA propagates through operations

mean(c(1, 2, NA, 4))        # NA
mean(c(1, 2, NA, 4), na.rm = TRUE)  # 2.33

Always use na.rm = TRUE when computing statistics on data that might contain missing values.

Mini Practice

  1. Assign your name and age to variables, then print them with cat()
  2. Use the pipe operator to take mtcars, filter by mpg > 20, and select columns
  3. Create a vector 1:10 and add 100 to it — observe vectorization
  4. Try x[0] on a vector — understand why it returns empty
  5. Use mean() on a vector containing NA — then use na.rm = TRUE

Next: variables and data types →

Related Topics

Frequently Asked Questions about Syntax

What is Syntax in R?

Syntax is a fundamental concept in R. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Syntax?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Syntax.

Why is Syntax important in R?

Syntax is essential for R development. Understanding this concept will help you write better code and solve real-world problems more effectively.