class: center, middle, inverse, title-slide .title[ # Intro to R ] .author[ ### PPG1004H ] .date[ ### Tutorial Week 2 ] --- # R and R studio <img src="img/rpic.png" width="100%" height="100%" /> Source: Modern Drive --- # Using R Studio Once you launch the R Studio App this is how it should look like: <img src="img/rstudio_picture.png" width="80%" height="60%" /> --- # R Studio Interface <img src="img/rladies.png" width="80%" height="60%" /> Source: R Ladies --- # The parts: The Editor The top left quadrant is the editor. This is where you write R code you want to save and use later. <img src="img/editor_picture.png" width="80%" height="60%" /> --- # The parts: The console You can find the console in the lower left quadrant of R Studio. \\ <img src="img/console_picture.png" width="80%" height="60%" /> The console is an interactive computer programming environment for R. It takes user inputs/commands, evaluates them, and returns the result to the user. --- # The parts: Environment/History The upper right corner is composed by two tabs. \underline{Environment:} Here you can see a list of all the objects you defined in the console. That is: functions, variables, datasets, values. You can also use it to import custom datasets manually and make them instantly available in the console. You can also inspect the environment of other packages you installed and loaded (more on packages at a later time). Play around with it - you can't break anything.\\ <img src="img/environment_picture.png" width="80%" height="60%" /> \underline{History:} Lists every single console command you executed since the last project started. It is saved into a hidden .Rhistory file in your project???s folder. You can choose not to save your environment after a session.\\ --- # The parts: Miscellaneous There are five tabs available in the lower right corner of RStudio. Files: File directory in your computer.\\ <img src="img/files_picture.png" width="80%" height="60%" /> Plots: Displays the plots you produce, you can edit them and save them as images. \\ Packages: Useful to install and use packages. (WE WILL LEARN WHAT THIS MEANS SOON) \\ Help:Contains the help directory and displays the help file when you ask for questions. This window is extremely useful as you will notice soon. \\ Viewer: Built-in browser. Not very used for the purposes of this class.\\ # R Studio <img src="img/r.png" width="60%" height="60%" /> --- # R Markdown Within R Studio, we can create a type of document called Markdown. - Neat way of combining code + text - Used for final documents/presentation of results/assignments - Has a visual editor that makes it look like a normal word processor --- # R as a calculator ```r 2+2 ``` ``` ## [1] 4 ``` ```r 2/3 ``` ``` ## [1] 0.6666667 ``` ```r log(10) ``` ``` ## [1] 2.302585 ``` ```r abs(-1) ``` ``` ## [1] 1 ``` ```r sqrt(9) ``` ``` ## [1] 3 ``` --- # Logical statements .med[Common logical operators: - == (is equal) - != (not equal) - < (greater than), > (less than) - & (and), | (or) ] --- # Logical statements ```r 1 < 2 ``` ``` ## [1] TRUE ``` ```r 1 == 2 ``` ``` ## [1] FALSE ``` ```r 2 != 2 ``` ``` ## [1] FALSE ``` ```r 1 > 0 & 2 > 0 ``` ``` ## [1] TRUE ``` ```r 1 < 0 | 2 <= 3 ``` ``` ## [1] TRUE ``` --- # The Grammar of R Verb(noun, adjective) is the same as *function(object, other arguments)* The other argument (adjective) is not always necessary --- # Functions Like in math: input, output Actions that you want R to carry out eg. `print()` --- # Objects R is based on objects: variables, functions, dataframes, etc. We usually want to store objects so we can work with them later. We do this by attributing a name to that object. ```r big_number <- 12345.6789 ``` --- # Objects - Objects can be of different types (or "class") - Most common class of objects: numeric, character, logical, matrix, data.frame, list, function. --- # Objects ```r year <- 2021 class(year) ``` ``` ## [1] "numeric" ``` -- ```r course_name <- "Quantitative Methods for Policy Analysis" class(course_name) ``` ``` ## [1] "character" ``` --- # Vectors (combining objects) A vector is a combination of more than one object (of the same class). We can create vectors with c() which stands for "combine". ```r courses <- c("PPG1004H", "PPG1005H", "GLA2034H") class(courses) ``` ``` ## [1] "character" ``` -- ```r avg_grade <- c(88, 95, 82) class(avg_grade) ``` ``` ## [1] "numeric" ``` --- # Datasets - Data frames are the core data structure in R - Data frames are *heterogenous*: the vectors in a data frames can each be of a different data type. - Columns are typically variables and rows are observations. --- # Datasets ```r data.frame(courses, avg_grade) ``` ``` ## courses avg_grade ## 1 PPG1004H 88 ## 2 PPG1005H 95 ## 3 GLA2034H 82 ``` --- # Packages/Libraries <img src="img/packages.png" width="80%" height="80%" /> -- .small[ | On phone | On R | |--------------|----------------------| | Download app | install.packages("") | | Open app | library() | ] --- #Loading libraries/packages If you load a library without installing it first, you will get this error: ```r library(BioConductor) ``` ``` ## Error in library(BioConductor): there is no package called 'BioConductor' ``` -- If you try to run a command from a package without loading it first, you will get this error: ```r stargazer(mtcars) ``` ``` ## Error in stargazer(mtcars): could not find function "stargazer" ``` --- # Basics of R: Errors and Warnings .med[Error: If you get an error, the command will not be executed. This can be due to many things (including silly spelling mistakes, missing parentheses, etc.)] ```r names <- "PPG1004H", "PPG1005H", "GLA2034H" ``` ``` ## Error: <text>:1:20: unexpected ',' ## 1: names <- "PPG1004H", ## ^ ``` --- # Basics of R: Errors and Warnings .med[In some occasions, R will warn you about this even before executing the code.] <img src="img/error.PNG" width="90%" height="90%" /> --- # Basics of R: Errors and Warnings .med[If you get a warning, the command will still be executed, but with some tweaking.] -- ```r x <- as.numeric(c("1", "2", "X")) ``` ``` ## Warning: NAs introduced by coercion ``` -- .med[Make sure that "tweaking" still gets you the result you want.] ```r x ``` ``` ## [1] 1 2 NA ``` --- # Where to find help .med[ 1) In R: - type ?mean - In "Help" window on lower-right pane 2) Google 3) StackExchange, StackOverflow 4) Package documentation, Package vignettes ] --- # Coding: What to save .med[Always save your script. **NEVER** save your environment upon exit. It's usually a good idea to start each session from scratch.] -- .pull-left[ <img src="img/saving.png" width="70%" height="60%" /> ] -- .pull-right[.small[ Each time you open R you're environment will be empty. This means that the objects you created in your previous session will not be saved (but you can always re-create them from the script).]] --- ## Practice Exercises 1. Using the console a. Calculate square root of 109090 b. Add 3 and 5 together. c. What number is larger: The log of 2000 or the square root of 51? (Try to do this in one line only.) d. What is the maximum number between: the square root of 200, seven times 2, and log of 3000. (Try to do this in one line in the console) --- 2. Google to find guidance/functions to: a. calculate standard deviation b. make a histogram of a variable c. import excel file --- 3. Download and save the documentation of the package ggplot2. (Hint: Use ?) --- 4. Find out what is wrong with the following line of code: install.package(car) (Hint: type it down on the console) --- 5. Try the exercise about summarizing income on your own. | Number of People | Income | |---------|--------| | 3 | $1,000 | | 1 | $1,100 | | 1 | $1,200 | | 2 | $2,300 | | 1 | $2,400 | | 2 | $2,500 |