TExcelTAD
Home › R › R Syntax

R Syntax

An R program is a sequence of expressions. R reads them top to bottom, evaluates each one and, if the result is visible and not assigned, prints it.

r · try it yourself
"R is fun"
5 + 5
x <- 10
x * 2
[1] "R is fun"
[1] 10
[1] 20

The line x <- 10 printed nothing: assignment returns its value invisibly. Writing x on its own (or x * 2) makes the value visible again.

One expression per line, or use semicolons

Normally each expression sits on its own line. You may put several on one line by separating them with ;, but that is rarely done in real code:

r · try it yourself
a <- 3; b <- 4; a + b
[1] 7

Lines that continue

R keeps reading while an expression is incomplete: an open bracket, an operator at the end of the line or a missing closing quote all mean "there is more". This lets you split long calls over several lines:

r · try it yourself
total <- 100 +
  250 +
  75
total

prices <- c(
  4.99,
  12.50,
  3.25
)
prices
[1] 425
[1]  4.99 12.50  3.25

Tip: Put the operator at the end of a line, not the start of the next. 100 on a line by itself followed by + 250 would be two complete expressions, and the result would be different.

Blocks with curly braces

Curly braces { } group several expressions into one block. The block's value is the value of its last expression. You'll use blocks in if statements, loops and functions:

r · try it yourself
result <- {
  width <- 4
  height <- 2.5
  width * height
}
result
[1] 10

Case sensitivity and names

R is case-sensitive: total, Total and TOTAL are three different names. Function names are case-sensitive too, so Mean(1:3) is an error while mean(1:3) works.

r · try it yourself
value <- 1
Value <- 2
c(value, Value)
Mean(1:3)
[1] 1 2
Error in Mean(1:3) : could not find function "Mean"

The error stopped the program: in a script, the first error ends the run.

Style conventions

Convention Example
Assign with <- count <- 0
Names in snake_case max_speed
Spaces around operators x + y, not x+y
Space after commas c(1, 2, 3)
Two-space indentation inside { } if (ok) { ↵ run() ↵ }

These are the conventions of the popular tidyverse style guide. R doesn't enforce them, but consistent style makes code much easier to read.

Test yourself

Why does x <- 5 on its own line print nothing?

  1. Assignments return their value invisibly
  2. R only prints strings
  3. It is an error
  4. x is not stored

What is the value of { a <- 2; a * 10 }?

  1. 2
  2. 10
  3. 20
  4. NULL

Are Total and total the same variable in R?

  1. Yes
  2. No, R is case-sensitive
  3. Only inside functions
  4. Only for numbers