R Syntax Basics
Prerequisites: How R code runs
A few rules cover most of what R code looks like.
One expression per line. No semicolons are needed.
Curly braces group code, and conditions go in parentheses:
if (10 > 5) {
cat("Ten is bigger\n")
}
Ten is bigger
Indentation is two spaces by convention (RStudio applies it with Ctrl + I). R doesn't require it, but it keeps code readable.
Comments start with #.
Case matters. Total and total are different names.
Names can contain letters, numbers, dots, and underscores, but can't
start with a number. The tidyverse style guide recommends
snake_case: total_price, mean_height.
Function calls use parentheses, and arguments can be named:
round(3.14159, digits = 2)
round(3.14159, 2)
[1] 3.14
[1] 3.14
Naming arguments makes code clearer, especially for less common ones.
Common mistakes
- Unfinished expressions. If a line ends with an operator like
+or an open parenthesis, R continues onto the next line — handy, but a missing)leaves the console waiting with a+prompt. - Putting
elseon a new line at the top level of a script. Keep it on the same line as the closing brace:} else {.