15.R Data Structures

vecto thì đồng nhất kiểu dữ liệu

list thì không đồng nhất kiểu dữ liệu

Data Structures

-Vectors: access element use V[ ]

fruits <- c("banana", "apple", "orange")

# Print fruits
fruits[1]
## [1] "banana"
fruits
## [1] "banana" "apple"  "orange"
length(fruits)
## [1] 3

-Lists access element use L[ [ ] ]

thislist <- list("apple", "banana", 50, 100)

# Print the list
thislist[[2]]
## [1] "banana"
thislist
## [[1]]
## [1] "apple"
## 
## [[2]]
## [1] "banana"
## 
## [[3]]
## [1] 50
## 
## [[4]]
## [1] 100
length(thislist)
## [1] 4

-Matrices access element use matran[?, ?]

my_matrix = matrix(1:6, nrow = 3, ncol = 2)
my_matrix[1, 2]
## [1] 4
my_matrix
##      [,1] [,2]
## [1,]    1    4
## [2,]    2    5
## [3,]    3    6
my_matrix[2, 2]
## [1] 5
my_matrix[, 2] #access all ncol
## [1] 4 5 6
my_matrix[2, ]
## [1] 2 5

-Arrays

my_array <- array(1:24, dim = c(4,2,3)) #c(n_row, n_col, n_lớp)
my_array
## , , 1
## 
##      [,1] [,2]
## [1,]    1    5
## [2,]    2    6
## [3,]    3    7
## [4,]    4    8
## 
## , , 2
## 
##      [,1] [,2]
## [1,]    9   13
## [2,]   10   14
## [3,]   11   15
## [4,]   12   16
## 
## , , 3
## 
##      [,1] [,2]
## [1,]   17   21
## [2,]   18   22
## [3,]   19   23
## [4,]   20   24
my_array[3, 2, 2]
## [1] 15
my_array[c(1),,1] #all pt row 1, class 1
## [1] 1 5
my_array[,c(1),1]#all pt col 1, class 1
## [1] 1 2 3 4

-Data Frames

id <- 1:3
name <- c("quy", "ngoc", "vu ")
class <- c("12A1", "11A3", "10A7")
my_data <- data.frame(id, name, class)
my_data
##   id name class
## 1  1  quy  12A1
## 2  2 ngoc  11A3
## 3  3  vu   10A7
my_data[1, ]
##   id name class
## 1  1  quy  12A1
my_data[2, 3]
## [1] "11A3"
my_data$name
## [1] "quy"  "ngoc" "vu "
#hoac la:
my_data[["name"]]
## [1] "quy"  "ngoc" "vu "

Factor()

gioi_tinh_vector <- c("Nam", "Nu", "Nu", "Nam", "Nam")

# Chuyển thành Factor
gioi_tinh_factor <- factor(gioi_tinh_vector)

print(gioi_tinh_factor)
## [1] Nam Nu  Nu  Nam Nam
## Levels: Nam Nu
levels(gioi_tinh_factor)
## [1] "Nam" "Nu"