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!
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)