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 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:
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:
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.
100on a line by itself followed by+ 250would 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:
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.
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?
- Assignments return their value invisibly
- R only prints strings
- It is an error
- x is not stored
What is the value of { a <- 2; a * 10 }?
- 2
- 10
- 20
- NULL
Are Total and total the same variable in R?
- Yes
- No, R is case-sensitive
- Only inside functions
- Only for numbers