Welcome to the wonderful world of R!


Objectives

Notes before we begin: R and RStudio rely on syntax, and are case-sensitive. They will not work if you type anything in incorrectly, include extra or are missing parentheses, use lowercase when you need uppercase, or uppercase when you need lowercase, etc. Think of everything you type in as a password. If you do not type your password in precisely, you cannot get into your account!

LEARNING R
1. Open RStudio. We will explore the interface together.

  1. Familiarise yourself with the different windows – the Console on the left pane, Environment and History tabs in the top right pane, and Files, Plots, Packages, Help, and Viewer tabs on the bottom right pane.

  2. Familiarise yourself with the dropdown tabs in the toolbar. (Here’s a fun hint! If you want to change the appearance of console window, go to Tools -> Global Options -> Appearance and select an Editor Theme. My personal favourite is “Chrome”, but you can select one that works best for you. Click “Apply”.)

2. R can be used as a calculator, AND a statistical analysis powerhouse.

  1. Let’s learn how to use it as a calculator. Type the following into the console.
     2+2 
  1. Let’s try some more calculations in R. Do you get the expected result?
     3-2
     3/2
     3*2 
     2^2 
     (2+3)*3

Great, you can do math in R!

3. We can also perform a wide variety of mathematical functions in R. Some functions include the following:

Calculate the following.

    log(4)
    sqrt(4)
    abs(-2)


4. With basic calculations you can just type in the syntax of the problem (e.g. 2 + 2), but to find the square root of a number we used “sqrt()”. sqrt() is a type of function, which is code that tells R to perform a specific task. The function is your action. Any words or numbers entered into the function are arguments, which define what the action acts upon, and how it runs. We will use functions a lot in R, especially for statistical analysis.

  1. Let’s look at the log() function again, except this time we want R to calculate it as base 10 rather than base e (natural log). Try the following.
     log(4, base = 10)

     ## Notice how we added a new argument, "base = 10" to tell the function log() to calculate base 10, rather than the natural log. Functions will have anywhere from one to multiple arguments, depending on the complexity of the function and what it can do.
  1. To know what else you can do with a function, we can ask R directly.
    Ask R for help on the log() function.
     ?log

     ## Documentation on the function should open in the bottom right pane. This documentation gives you information on the function (description), how to use it (usage), the arguments, examples, and much more. 


5. We can also assign values to variables (handy when analysing data!).

  1. Assign x a value of 4 (Shortcut for <- : Alt + -)
     x <- 4

     # Notice that we used <- instead of =. You should never use an = sign when assigning variables! It will work, but causes errors and conflicts within functions. Best to avoid! 
  1. There will be no output because you are just assigning a variable. To see the value of your variable, you must type in your variable again.
     x
  1. Use your variable in some basic calculations. Do you get the correct value?
     x + 3
     x - 2
     x*2
  1. You can reassign x to another value at any point.
    Reassign it to 32.
     x <- 32
     x
  1. Type in a capital X. Why does this produce the following error?
     X
## Error:
## ! object 'X' not found
  1. We can use full names instead of one letter when assigning variables, so we can keep track of what we are analysing. Be as descriptive as possible so you know what it means, but don’t make them too long! Otherwise, they become a pain to type over and over and over…Also, names cannot have spaces. (If you want a name with multiple words, you can use underscores "_", but this is not recommended. They’re a pain to to type, and often run into errors for big analyses).

    Assign the value of 64 to the height of an adult human.

     height <- 64
     height


6. So far, we have only worked in the console. When you work in the console, your input and output are NOT saved. Think of it as a scientific calculator – once you shut off the calculator, all of your inputs are lost. We usually want to be able to save our input so we can re-run analyses, remind ourselves of what we’ve done, and have something to work from the next time we open RStudio. To do this, we use and save R scripts.

  1. Create a new script: Click on the upper left icon (white paper with + button) -> Select “R Script” from the dropdown menu (alternatively, use the shortcut Ctrl + Shift + N).

  2. Write the following in your script (Shortcut for #: Shift + 3)

# Filename: bio272-lecture1
# Title: R Exercise 1 - Intro to R 
# Author: Write your full name here
# Date: Month Day Year (write the actual date here)

# Description: This script is...write a description of what this script is for. You will thank yourself later!
## Tip 1 (DO NOT WRITE): Notice we use # to denote a comment or annotation. I like to use ## but that's just personal preference! Anything with a # in front will not run in the console when you run your script later.

## Tip 2 (DO NOT WRITE): If you do not want to type a new # symbol everytime you go to a new line, you can change the settings in R. In the toolbar, go to Tools -> Global Options -> Code. Under "General" you will see a check box for "Continue comment when inserting new line". Check this box. To apply settings click on Apply, and OK.
  1. Let’s see how to use and run a script.
    Type the following in your script. When done, either go to each line and click on the button that says “Run” OR highlight the entire script and then click “Run”. Do you get the same answers as before when just using the console? (Shortcut to Run: Ctrl + Enter)
    (Shortcut to Run entire script: Ctrl + Shift + Enter)
     # Basic calculations in R:
     2+2 # addition
     3-2 # subtraction
     3*2 # multiplication
     3/2 # division
     2^2 # exponents
     (2+3)*3 # stacking operations
  1. Save your script: File -> Save As -> Save to Desktop. Email the file to yourself, or save to USB if you wish to keep this for future study/practice. I recommend you do this every class so you can write notes during exercises and have something to practice from at home.


Now it’s time to practice on your own.

  1. In your R script, go back to the previous exercises (3, 4a-b, 5a-f) and type them is as we did in the console. Add comments to tell yourself what each line of code does. Then, run and check your results. Are they the same as before?

  2. A researcher wants to come up with a name for each of the following variables. Come up with appropriate names that can be used in R and type them into your script.
    a. Body temperature in Celsius
    b. How much aspirin is given per dose for a patient
    c. Number of televisions per household
    d. Height (inlcuding neck and extended legs) of giraffes

  3. In your script, write code for the following calculations. Run the code and write values for your calculations as comments in your script.
    a. 15 x 17
    b. \(13^3\)
    c. log(14) (natural log)
    d. log(100) (use base 10)
    e. \(\sqrt{81}\)