{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "jRNjXbUlTQPB" }, "source": [ "# Control Structures\n", "\n", "This lesson will cover how R code uses loops and conditionals, just like Python." ] }, { "cell_type": "markdown", "metadata": { "id": "m7votYy_Yh7f" }, "source": [ "## Conditions\n", "\n", "R uses a model similar to Python for control structures. The `if` and `else if` statements require a logical test that results in `TRUE` or `FALSE`, while `else` acts as a catch-all with no condition.\n", "\n", "In terms of syntax, the main differences between R and Python are:\n", "\n", "- Conditions are enclosed in parentheses.\n", "- There is no `:` after the condition statement to indicate the code block to execute.\n", "- The code block to run is enclosed in `{}`, rather than being indicated by indentation.\n", "- `elif` in Python is called `else if` in R.\n", "\n", "On the other hand, comparison operators in R are the following:\n", "\n", "| Operator | Name | Example |\n", "|---|---|---|\n", "| `==` | Equals | `x == y` |\n", "| `!=` | Not equals | `y != x` |\n", "| `>` | Greater than | `x > y` |\n", "| `<` | Less than | `y < x` |\n", "| `>=` | Greater than or equal to | `x >= y` |\n", "| `<=` | Less than or equal to | `y <= x` |\n", "\n", "Let's have a look at different examples:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "id": "yPHhbOulYmBw" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1] \"y is greater than x\"\n" ] } ], "source": [ "x <- 14\n", "y <- 120\n", "\n", "if (y > x) {\n", " print(\"y is greater than x\")\n", "}" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "id": "4_MdL-xUZH5A" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1] \"x and y are equal\"\n" ] } ], "source": [ "x <- 33\n", "y <- 33\n", "\n", "if (y > x) {\n", " print(\"y is greater than x\")\n", "} else if (x == y) {\n", " print(\"x and y are equal\")\n", "}" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "id": "XDnNHcz4ZWWX" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1] \"x is greater than y\"\n" ] } ], "source": [ "x <- 120\n", "y <- 44\n", "\n", "if (y > x) {\n", " print(\"y is greater than x\")\n", "} else if (x == y) {\n", " print(\"x and y are equal\")\n", "} else {\n", " print(\"x is greater than y\")\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "R provides an `ifelse` function, which is very useful for converting data into boolean values." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "