Week 1 - A.Reviews of Basics
Week 1 - A.Reviews of Basics
Review of basic R
In this section, we revisit basic concepts and usage of R. You may skip the section if you are comfortable
using R.
2 / 5 + (5 - 4) * 1
## [1] 1.4
## [1] TRUE
plot(rnorm(25))
my_number <- 5
my_number
## [1] 5
characters:
logicals:
## [1] TRUE
https://rconnect.utstat.utoronto.ca/content/a57e9d9b-336e-4f49-9347-afee2f53a192/#section-review-of-basic-r 1/4
25/01/2024, 12:30 Week 1: Review and Introduction to Data Analysis
## [1] 2 3 7
my_vector[1]
## [1] 2
my_vector[c(1, 3)]
## [1] 2 7
## [1] 7
my_vector[c(T, F, T)]
## [1] 2 7
n <- 5
numeric(n) # numbers
## [1] 0 0 0 0 0
character(n) # characters
logical(n) # logicals
Exercise 1
Create a vector that consists of day of your birthday and your first name. Print the vector and comment on its data
type.
Functions
In R, a function is in the following form:
You can store the result of a function with result <- function_x(...)
https://rconnect.utstat.utoronto.ca/content/a57e9d9b-336e-4f49-9347-afee2f53a192/#section-review-of-basic-r 2/4
25/01/2024, 12:30 Week 1: Review and Introduction to Data Analysis
[1] 12
You can look at the help page of each function with ?<function name> . Whenever you need help using a function,
try the help page first. A quick search on the Internet will often provide many examples as well.
1 ?sample
2
3
There are also a plenty of resources and examples online for most R functions.
[1] 10
Exercise 2
Create a function named diff_in_absolute_diff() that takes 4 numbers – say, w , x , y , and z — and computes
| w − x | − |y − z |
[1] 5
## [1] 15 30 45 60 75
Many R functions automatically broadcast the operation to each element resulting in a vector of same size.
x + y
## [1] 15 30 45 60 75
Exercise 3
https://rconnect.utstat.utoronto.ca/content/a57e9d9b-336e-4f49-9347-afee2f53a192/#section-review-of-basic-r 3/4
25/01/2024, 12:30 Week 1: Review and Introduction to Data Analysis
| w − x | − |y − z |
for each element of the following vectors.
w <- c(1, 2, 3, 4, 5)
x <- c(10, 20, 30, 40, 50)
y <- c(5, 10, 15, 20, 25)
z <- c(50, 40, 30, 20, 10)
The vectors w , x , y , z , and the function diff_in_absolute_diff() have been predefined for your use in the
following chunk. Use the for-loop to compute and save the resulting values to the vector u .
1 # use a loop
2 u <- numeric(5)
3 for (i in 1:5) {
4 u[i] <- diff_in_absolute_diff(w[i], x[i], y[i], z[i])
5 }
6 u
In the code chunk below, the vectors are directly used as inputs. Compare the results from the loop
version above.
1 # diff_in_absolute_diff() is a vectorized
2 u <- diff_in_absolute_diff(w, x, y, z)
3 u
NEXT TOPIC
https://rconnect.utstat.utoronto.ca/content/a57e9d9b-336e-4f49-9347-afee2f53a192/#section-review-of-basic-r 4/4