R Basics

2. Comparisons & Logic

Every day, we make thousands of tiny judgements that lead to bigger actions. Based on the information available, we will make what we judge to be the right decision. The programs that you will write will be exactly the same - we will feed it information, it will evaluate it and proceed accordingly.

On the pitch, do I take a shot or lay it off for a better chance elsewhere? In the manager's office, does he sign a new goalkeeper, or show faith in the academy? Decisions are made on the information available - let's take a look at how this is done in R.

Comparison Operators

You may be familiar with comparison operators from other programming languages or even in Excel. These are used to ask the relationship between two values. Is one bigger than another? Are they the same?

They will return with either 'True' or 'False'. Eventually, we will write programs that make decisions based on these evaluations.

Let's use some simple examples with numbers:

          # Is four greater than three?
          4 > 3

          ## [1] TRUE
          # Is four less than three?
          4 < 3

          ## [1] FALSE
          # Is 20 less than or equal to 21?
          20 <= 21

          ## [1] TRUE
          # Does 44 equal 44? We use 2 equals signs here!
          44 == 44

          ## [1] TRUE

Remember our variables section? Let's assign a skill ranking to some players and evaluate them.

          # Our skill ranking system assigns two players a ranking, Who is better?

          Garrerd = 99
          Landard = 98

          Garrerd > Landard

          ## [1] TRUE

Logic Operators

Logic operators allow us to use multiple comparisons together. This is really useful as we can quickly ask more complex questions from our programs.

Let's take the example above. Why don’t we check if we can afford to purchase the better player, assuming they both cost the same?

          # Garrerd = 99 and Landard = 98 as in the last example
          # Check that Garrerd is better AND that can we afford them?

          Budget = 5000000
          PlayerCost = 4000000

          (Garrerd > Landard) & (Budget >= PlayerCost)

          ## [1] TRUE

Sign him up!

By using the '&' symbol, we test if both things are true. If just one has to be true, we can use the '|' symbol instead.

In this new example, our star striker gets a £1,000,000 bonus if she scores more than ten goals or makes at least 15 assists. Let's test to see if she did it.

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!