Logical Conditions & if/else in R
Interactive beginner R tutorial on logical conditions: comparison operators, & | ! and %in%, if/else blocks and the vectorized ifelse(). Run real R in your browser.
Every filter, every decision your code makes, rests on a TRUE or FALSE test. Everything below is a live R console β edit the code and press Run Code.
Watch: logical conditions & if/else
Comparisons, combining them with &/|/%in%, and branching with if/else and the vectorized ifelse().
Download the R script Β· βΆ Practice in the playground β or edit and run each snippet below.
Comparisons return TRUE / FALSE
>, <, == (equal) and != (not equal) test a condition β element by element on a vector:
Combine conditions
& is and, | is or, ! is not, and %in% tests membership in a set:
if / else
Run one block when a single condition is true, another when itβs false:
ifelse() works on a whole vector
When you need an answer per element, use ifelse() β the workhorse for recoding data:
Your turn
Next: Data frames β β Rβs table for real datasets.