Skip to content

Step 1 of 5 · Reading · ~1 min

Learn

Control Flow

x <- 10
if (x > 0) {
    cat("positive\n")
} else if (x < 0) {
    cat("negative\n")
} else {
    cat("zero\n")
}

Logical operators: && (and), || (or), ! (not). Use double && and || for SCALAR conditions inside if. Single & and | are vectorized - they return a vector of TRUE/FALSE.

if (x > 0 && x < 100) { ... }    # scalar - what you want for if()
ages > 18 & ages < 65            # vector - for filtering

ifelse(test, yes, no) is the vectorized if - works element-wise:

ages <- c(15, 30, 50, 70)
ifelse(ages >= 18, "adult", "minor")
# "minor" "adult" "adult" "adult"

Two syntax rules that stop R scripts dead

The remainder operator is %%, not %. A bare % in R opens a custom infix operator such as %in%, so n % 3 is not an incomplete expression - it is a parse error, unexpected input. %/% is integer division:

7 %% 3     # 1   remainder
7 %/% 3    # 2   integer division

else must sit on the same line as the closing brace. At the top level of a script R finishes parsing the if at the }, then meets an else attached to nothing and stops with unexpected 'else':

if (x > 0) {
    cat("positive\n")
}
else {                    # top level: syntax error
    cat("other\n")
}

if (x > 0) {
    cat("positive\n")
} else {                  # correct
    cat("other\n")
}

Inside a function body the newline form does parse, because the enclosing braces tell R the expression is unfinished. That is a habit worth not forming - it breaks the moment the same code moves to the top level.

Up nextLoops (and Why You Rarely Need Them)Control Flow

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…