When we’re programming in R (or any other language, for that matter), we often want to control when and how particular parts of our code are executed. We can do that using control structures like if-else statements, for loops, and while loops.

Control structures are blocks of code that determine how other sections of code are executed based on specified parameters. You can think of these as a bit like the instructions a parent might give a child before leaving the house:

“If I’m not home by 8pm, make yourself dinner.”

Control structures set a condition and tell R what to do when that condition is met or not met. And unlike some kids, R will always do what we tell it to! You can learn more about control structures in the R documentation if you would like.

In this tutorial, we assume you’re familiar with basic data structures, and arithmetic operations in R.

Not quite there yet? Check out our Introductory R Programming course that’s part of our Data Analyst in R path. It’s free to start learning, there are no prerequisites, and there’s nothing to install — you can start learning in your browser right now.

install.packages(“Dataquest”)

Start learning R today with our Introduction to R course — no credit card required!

SIGN UP

(This tutorial is based on our intermediate R programming course, so check that out as well! It’s interactive and will allow you to write and run code right in your browser.)

Comparison Operators in R

In order to use control structures, we need to create statements that will turn out to be either TRUE or FALSE. In the kids example above, the statement “It’s 8pm. Are my parents home yet?” yields TRUE (“Yes”) or FALSE (“No”). In R, the most fundamental way to evaluate something as TRUE or FALSE is through comparison operators.

Below are six essential comparison operators for working with control structures in R:

  • == means equality. The statement x == a framed as a question means “Does the value of x equal the value of a?”
  • != means “not equal”. The statement x == b means “Does the value of x not equal the value of b?”
  • < means “less than”. The statement x < c means “Is the value of x less than the value of c?”
  • <= means “less than or equal”. The statement x <= d means “Is the value of x less or equal to the value of d?”
  • > means “greater than”. The statement x > e means “Is the value of x greater than the value of e?”
  • >= means “greater than or equal”. The statement x >= f means “Is the value of xgreater than or equal to the value of f?”

#data science tutorials #beginner #for loop #for loops #if #if else #learn r #r #r tutorial #rstats #tutorial #tutorials #while loop #while loops

How to Use If-Else Statements and Loops in R – Dataquest
1.85 GEEK