Syntax
Here, we learn about the general syntax in R, including assignment operators, curly braces and the else statement.
General Syntax
- For assignments, use
<-
not=
.
Press + to interact
## GOODx <- 5# BADx = 5
- Do not terminate your lines with semicolons
;
or use semicolons to put more than one command on the same line. (Semicolons are not necessary, and are omitted for consistency with other Google style guides.)
Press + to interact
## GOODx <- 5# BADx <- 5;
Curly Braces
An opening curly brace should never go on its line; a closing curly brace should always go on its line.
- Always begin the body of a block on a new line.
You may omit curly braces when a block consists of a single statement; however, you must consistently either use or not use curly braces for single statement blocks.
Press + to interact
# GOODif (is.null(ylim)) {ylim <- c(0, 0.06)}if (is.null(xlim)) {xlim <- c(0, 0.06)}# GOODif (is.null(ylim))ylim <- c(0, 0.06)if (is.null(xlim))xlim <- c(0, 0.06)# BADif (is.null(ylim)) ylim <- c(0, 0.06)if (is.null(xlim)) {xlim <- c(0, 0.06)}
Surround else
with braces.
An else
statement should always be surrounded on the same line by curly braces.
Press + to interact
# GOODif (condition) {# one or more lines} else {# one or more lines}# BAD:if (condition) {# one or more lines}else {# one or more lines}# BADif (condition)# one lineelse# one line