John Doe
2025-06-05
2.3 Lab: Introduction to R
In this lab, we will introduce some simple R commands to understand
how R works.
2.3.1 Basic Commands
# Creating a numeric vector with 4 elements
x <- c(1, 3, 2, 5)
# Printing the vector x
x
## [1] 1 3 2 5
# Updating x with a new set of values
x = c(1, 6, 2)
# Printing the updated x
x
## [1] 1 6 2
# Creating another numeric vector with 3 elements
y= c(1, 4, 3)
# Checking the number of elements in x
length(x)
## [1] 3
# Trying to find the length of y (this will give an error because y
doesn't exist yet)
length(y)
## [1] 3
# Adding x and y (will also give an error unless y is defined)
x + y
## [1] 2 10 5
, # Listing all current objects in the environment
ls()
## [1] "x" "y"
# Removing objects x and y from the environment
rm(x, y)
# Checking again to confirm they are removed
ls()
## character(0)
# Removing everything from the environment
rm(list = ls())
# Asking for help on the matrix function
?matrix
## starting httpd help server ... done
# Creating a 2x2 matrix using named arguments
x <- matrix(data = c(1, 2, 3, 4), nrow = 2, ncol = 2)
x
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
# Creating a matrix without naming the arguments (just positional)
x <- matrix(c(1, 2, 3, 4), 2, 2)
# Creating a matrix where values are filled by row instead of column
matrix(c(1, 2, 3, 4), 2, 2, byrow = TRUE)
## [,1] [,2]
## [1,] 1 2
## [2,] 3 4
# Taking square root of each element in x
sqrt(x)
## [,1] [,2]
## [1,] 1.000000 1.732051
## [2,] 1.414214 2.000000
# Squaring each element in x
x^2
## [,1] [,2]
## [1,] 1 9
## [2,] 4 16