Overview
Container variables store collections of data.
Common types include vectors, lists, matrices, and data frames.
2024
Container variables store collections of data.
Common types include vectors, lists, matrices, and data frames.
A vector is a basic data structure that holds elements of the same type.
Created using c()
function.
# Creating a numeric vector numeric_vector <- c(1, 2, 3, 4, 5)
[ ]
for accessing elements.# Accessing the third element numeric_vector[3]
## [1] 3
Lists can hold elements of different types.
Created using list()
function.
# Creating a list mixed_list <- list("a", TRUE, 3, 1.5)
Use double square brackets [[ ]]
for single elements.
Use $
to access elements by name.
# Accessing the first element mixed_list[[1]]
## [1] "a"
# Assuming the list has names named_list <- list(name1 = "a", name2 = TRUE) named_list$name2
## [1] TRUE
A matrix is a two-dimensional collection of elements of the same type.
Created using matrix()
function.
# Creating a matrix my_matrix <- matrix(1:9, nrow = 3)
[row, column]
to access elements.# Accessing element in the first row, second column my_matrix[1, 2]
## [1] 4
data.frame()
function.# Creating a data frame my_data_frame <- data.frame(column1 = 1:4, column2 = c("a", "b", "c", "d"))
$
to access columns by name.[ , ]
for accessing elements by row and column.# Accessing a column my_data_frame$column1
## [1] 1 2 3 4
# Accessing element in the first row of the second column my_data_frame[1, "column2"]
## [1] "a"
How do you access the second element of a list named my_list
?
my_list[2]
my_list[[2]]
my_list$2
my_list(2)
my_list[[2]]
is used to access the second element of a list.How do you access the third element of a numeric vector named numeric_vector
?
numeric_vector(3)
numeric_vector[3]
numeric_vector[[3]]
numeric_vector$3
numeric_vector[3]
is used to access the third element of a numeric vector.Given a matrix my_matrix
with at least 2 rows and 2 columns, how do you access the element in the second row and first column?
my_matrix[2, 1]
my_matrix[[2, 1]]
my_matrix(2, 1)
my_matrix$2,1
my_matrix[2, 1]
is the correct way to access the element in the second row and first column of a matrix.How do you access the value in the first row of a column named column2
in a data frame df
?
df[1, "column2"]
df[[1, "column2"]]
df$column2[1]
df[1, "column2"]
and df$column2[1]
are correct ways to access the value in the first row of column2
in a data frame.