Upper left: Text Editor
Lower left: Console
Upper Right: Environment
Lower Right: Files / Plots / Help
Just typing. This isnโt code.
1 + 2
1 + 2
## [1] 3
create a vector
v <- c(1, 4, 9, 16, 25)
operations on vectors
Take square root of every element of a vector
sqrt(v)
## [1] 1 2 3 4 5
v + 1
## [1] 2 5 10 17 26
A function applied to a vector applies the function to each element.
to update vector v (assign as the same name)
v <- sqrt(v)
to undo, run the original function again:
v <- c(1, 4, 9, 16, 25)
Usually good practice to give new names to new things:
w <- sqrt(v)
Which elements of v are bigger than 10?
v > 10
## [1] FALSE FALSE FALSE TRUE TRUE
Other operations: greater than or equal to >= Less than < Less than or equal to <= Equals == (two equal signs) Not equals !=
Create new vector of elements of logicals for if elements of v are > 10.
u <- v > 10
How many elements are greater than 10?
2, just by counting
Ask R:
sum(u)
## [1] 2
How do we write functions in R?
structure
name_of_function <- function(variable1, variable6, pizza){
variable1 + variable6*pizza
}
Recall the birthday problem. Suppose we have a group of k people and each chooses a number between 1 and n.
The probability of a match is
1 - n!/((n-k)!*n^k)
\[ 1 - \frac{n!}{(n-k)! n^k} = 1 - \binom{n}{k}\frac{k!}{n^k} \]
Write function to input n,k and return probability
prob_bday_match <- function(n_bdays, k_people){
1 - choose(n_bdays, k_people)*factorial(k_people)/(n_bdays^k_people)
}
How to plot in R (basic)?
To plot function of 1 variable:
need vector of inputs
need vector of corresponding outputs
Goal: Plot birthday probability for 25 students choosing from numbers between 50 and 25000.
View function at equally spaced points in domain
n_bdays <- seq(from = 50, to = 1000, by = 25)
Evaluate function on n_bdays
probs <- prob_bday_match(n_bdays, 25)
Use plot function applied to vectors of inputs and outputs
plot(n_bdays, probs)