R Basics

8. Creating functions

In previous posts, we have seen a couple a couple of examples of functions – print() being just one of them.

As you know, functions are ways for us to give an instruction to a program. Out of the box, R has lots of them – and packages add even more. But there are many instances when we might want to create our own. They can save us repeating code, they can give us code that we share with other people or future programs that we will write.

Creating them is simple:

          
    doubleMe <- function(number){
      return(number * 2)
    }

    doubleMe(2)

    ## [1] 4
          
  

In just two lines, we have introduced a new function called ‘doubleMe’! Let’s break this down bit by bit:

The first line uses the function definer function and tell R to save it as a name, in this case doubleMe. We then tell it what arguments it is going to need – any we gave this function one argument, called ‘number’. ‘Number’ is just a name, we could have called this anything, but it helps us to give a comprehensible name. Why make life more difficult?!

After the arguments list in brackets, add a {.

On the next line we give instructions as to what to do with these arguments. In this example, we return the ‘number’, multiplied by 2!

Let’s create a function that creates a Tweet for our live text commentary:

        
    newTweet <- function(player, action, success){

        tweet <- ""
        if(success){

          if(action == "pass"){
            tweet <- paste0(player, " plays a ", action, ". The team keep possession")
          }else{
             tweet <- paste0(player, " plays a ", action, ". GOOOOOAAAAAAALLLLLL")
          }

        }else{

          if(action == "pass"){
            tweet <- paste0(player, " plays a ", action, ". The pass is unsuccessful")
          }else{
             tweet <- paste0(player, " plays a ", action, ". No goal this time!")
          }

        }
      return(tweet)
    }

    newTweet("Pearlo", "shot", TRUE)
    ## [1] "Pearlo plays a shot. GOOOOOAAAAAAALLLLLL"
        

We have just created a program that creates tweets for us, based on three arguments – player, action and success.

It takes the first two arguments and creates the first sentence in the tweet. It then takes the True or False value in success to decide what to add to the end of the tweet with some nested if statements. Hopefully these are simple enough to follow along with!

The function finally returns the new tweet, which we can manually add to our feed. Did you know there is a Twitter package for Python that will allow you to post directly to Twitter?! A lesson for another day.

Summary


Here, we have seen how to define functions with the following structure:

functionName <- function(Arguments){ ---do something with arguments--- }

This allows us to write reusable code that will make our programs smarter, tidier and sharable! They incorporate if statements, for loops and everything else that you have learned and will learn in R.

In our example, we created a small function that creates tweets for us for a live text commentary, that save us typing out the same things repeatedly. It wasn’t particularly smart, but we’ll get there!

Next Lessons...


  1. Numbers, Variables & Strings
  2. Comparisons & Logic
  3. If Statements
  4. For Loops
  5. While Loops
  6. Lists
  7. Packages
  8. Creating Functions
  9. Random Numbers with Expected Goals

This is a R conversion of a tutorial by FC Python. I take no credit for the idea and have their blessing to make this conversion. All text is a direct copy unless changes were relevant. Please follow them on twitter and if you have a desire to learn Python then they are a fantastic resource!