Friday, February 15, 2019

Lesson 5: Loops & If-Else Statements in R

It's been a while, but I'm back after several months!

In this post we're going to talk about For-Loops, While-Loops, and If-Else Statements.  I'm really excited about this post because, this is where we really get into giving our R-Scripts the ability to make decisions on our behalf!

So, Let's get Started.

PART 1: FOR-LOOPS
Let's start by creating a simple data frame.

my_df <- as.data.frame(c(1, 2, 3, 4, 5))

Next, let's create a user friendly column name.

names(my_df) <- "data"

And, just out of curiosity, let's see how many rows are in this dataframe.

nrow(my_df)

Okay so there are 5 rows in this data frame, so we'll write a for-loop to perform a calculation of mulitiplying the original number in a given row by 10 on each of the 5 rows.

for(i in 1:nrow(my_df)){
  
  my_df$for_loop[i] <- my_df$data[i] * 10

  }

This loop is saying for each row "i" from row 1 to 5, take the original data value in that row and muliply it by 10.

You did it!  Your first for-loop!  Well done!


PART 2: WHILE-LOOPS
I typically use While-Loops when I'm not certain how many times I need to perform a calculation or apply a function.

Let's pretend I didn't know how many rows where in the data frame "my_df" and try to do the same type of calculation as before except this time using a While-Loop.

i <- 1
while(i <= nrow(my_df)){
  
  my_df$while_loop[i] <- my_df$data[i] * 10 
  
  i <- i + 1
}

Success!  Same results as we got with the For-Loop!  See how much fun we're having?


PART 3: IF-ELSE STATEMENTS
If-Else statements are useful if you want to make decisions in your code... kind of like choose your own adventure books.  IF "this" then "do this" ELSE if it's not "this" then do "that"... get it?

So let's continue with the current "my_df" data and lets say if the row is the third row multiply by 20 and all other rows, multiply by 20.  Let's use the for-loop with our if-else statement this time!

for(i in 1: nrow(my_df)){

    if(i == 3){
    
    my_df$if_else[i] <- my_df$data[i] * 20 
    
    }else{
      
      my_df$if_else[i] <- my_df$data[i] * 10 
      
    }
  
  }

Nice work!  You did it!  That wasn't so bad right?!

Now get creative and create some examples for yourself to practice your new skillz!

CONGRATULATIONS!  YOU'RE DONE WITH LESSON #5

DOWNLOAD CODE Here is the code from my GitHub gist "R Lesson 5 - Loops and If-Else Statements in R" in case you'd rather just copy and paste it and then play around with it.


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.