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.