Wednesday, February 20, 2019

Lesson 6: Functions in R

I'm really excited about this lesson!

Functions are a great way to leverage your creativity while coding.  We're going to create a simple function to show how they work and then we're going to create a couple practical functions.  One function will help us determine the square footage of a home and another to help us determine the monthly payment on a Tesla Model S and that $250,000 house we've being keeping an eye on.

To put it simply, functions are chunks of code that you can reuse over and over throughout your script.  This can help save you time writing code and will keep your scripts shorter since you don't have to re-write multiple lines of code.  It's all about convenience & efficiency!

PART 1:  OUR FIRST FUNCTION
We are going to create a simple first function that multiplies two numbers together and then displays the results.

We use R's "function()" function to define our function and the variable that we assign the function to becomes the name of the function itself which we can then call anytime we want to in the R-Script.

A function needs us to define arguments or values that will be needed for calculations contained in it.  In this example, we have two arguments, "first_number" and "second_number".  


my_function <- function(first_number, second_number){

  answer <- first_number * second_number

  cat("My function calculates: ", first_number," X ",second_number, " = ", answer, ".\n", sep = "")

  cat("Aren't functions great!?")

}

Our function use R's concatenate or "cat()" function to display a message to the user.

Now let's try it out and see if we get 20!

my_function(2,10)

Success!  It worked!


PART 2:  OUR SECOND FUNCTION 
The next example will be a practical application using functions.
Let's create a function called "room_area" which needs the length and width of the room to calculate the area in square feet.

room_area <- function(length, width){
  area <- length * width
  }

Next let's say a house has 7 rooms, let's use that function to estimate the square footage of that house.

living_room <- room_area(length = 20, width = 20)
dining_room <- room_area(length = 20, width = 20)
kitchen <- room_area(length = 15, width = 25)
bath_1 <- room_area(length = 10, width = 10)
bath_2 <- room_area(length = 10, width = 20)
bed_1 <- room_area(length = 15, width = 20)
bed_2 <- room_area(length = 15, width = 15)
bed_3 <- room_area(length = 15, width = 15)

Now let's add up the square footage of all the rooms.

home_area <- living_room + dining_room + kitchen + bath_1 + bath_2 + bed_1 + bed_2 + bed_3

2,225 sq. ft.!  That's a nice size home!

home_area

Are you starting to see the convenience of functions?!


PART 3: LET'S GET THE FUNCTION OUTTA HERE!
Here's a final practical application of using a function.
Let's create a function that will allow us to calculate the monthly payment on a fixed interest loan or mortgage.
We'll need to know the annual interest rate, the original loan amount, the down payment amount (if any), and finally the number of years to amortize the loan or mortgage.

monthly_payment <- function(annual_interest_rate, original_loan_amt, down_payment=0, number_of_years){
  payment <- round(((annual_interest_rate/(12*100)) * (original_loan_amt-down_payment)) / (1-(1+(annual_interest_rate/(12*100)))^-(number_of_years*12)),2)
  cat("Your monthly payment will be $", payment, " for ", number_of_years, " years", sep = "")
}

What would our monthly payment be for that new Tesla Model S at $99,500 if we amortize it over 5.5 years at a fixed-interest rate of 4.75%.

monthly_payment(4.75, 99500, 0, 5.5)

$1,716.03 per month for 5.5 years for a Tesla Model S?!

We may want to consider the Tesla Model 3 instead... ;P

Okay, now let's see what a $250,000 house will cost us each month if we amortize it over 30 years at a fixed-interest rate of 4.0%.

monthly_payment(4.00, 250000, 0, 30)

$1,193.54 per month for 30 years for that house we've been watching... better not quit our day job!

That's it for this lesson!  Now get practicing!

CONGRATULATIONS!  YOU'RE DONE WITH LESSON #6

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





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.