The R console
- Start by opening RStudio
- The pane on the left is the R console
- Note that each pane has multiple tabs
Using R as a calculator
2+2
2 + (incomplete)
2 + two (error)
Installing packages
install.packages('tidyverse')
- check to makes sure everyone has it installed
- install from Tools menu
Going beyond simple calculations in R
Variables
a <- 2 (point out environment tab)
a (print value)
a+a
b <- a + a
b
Vectors
u <- c(0, 0.25, 0.5, 0.75, 1)
u
u + 2
u
u <- u + 2 (then back up to original u)
mean(u)
v <- c(-1, 0, 1, 0, -1)
u + v
x <- seq(0, 1, by = 0.1)
x
?seq
Basic plotting
- R typically creates plots from data
- If we want to plot \(y=x^2\) need to define vectors x and y with the data you want to plot
y <- x^2
y
plot(x, y)
plot(x, y, type = 'l')
plot(x, y) then lines(x, y)
- can customize!
Working with data
- Check your working directory(folder):
getwd()
dir()
- We will be working primarily with the data that is already a part of a package but if you have data in a file, R will assume that it is located in this directory.
- Let us try to read into R a data file. Download a file from here. (Usually it will be downloaded into folder "Downloads" on your computer).
- Move or copy this file into R working directory
- Read this file:
data_set <- read.csv('loan50.csv')
- Take a look at the data_set:
data_set
- Now, let us access the same data as a part of 'openintro' package
- Install package 'openintro':
install.packages('openintro')
- Load two installed packages into R:
library('tidyverse')
library('openintro')
- Take a look at the file loan50:
loan50
- Note that it is presented differently, since 'loan50' dataset is being stored as a data frame. More about it later.
Intro to piping
- Try the following code:
sum(3,2)
- Now try the piping:
3 |> sum(2)
- We can read the code as: “take 3 and pipe it into the sum() function. The pipe operator |> tells R to pass the object that comes before it into the first argument of the function that comes after it. Mathematically, x pipe f(y) becomes f(x, y), since x is piped into the first argument of the function f()
- Another way to pipe is to use operator %>%
3 %>% sum(2)
- You don't need to worry about all of the differences between |> and %>% at the moment but, in general, |> is a simplified version of %>%. For example, using %>% can be used to replace several arguments of a function: x %>% f(.,./2) becomes f(x,x/2)