Giới thiệu

Tài liệu này minh họa các thao tác cơ bản với dữ liệu Iris trong R, bao gồm:


Chuẩn bị thư viện và dữ liệu

library(dplyr)

# Đọc dữ liệu
iris_data <- read.csv("C:/Users/Admin/OneDrive/Tài liệu/iris.csv")


# Xem 6 dòng đầu
head(iris_data)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa

Chọn các biến số

# Loại bỏ cột Species
numeric_data <- iris_data[, -5]

# Xem cấu trúc
str(numeric_data)
## 'data.frame':    150 obs. of  4 variables:
##  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
##  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
##  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
##  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...

Tính trung bình và độ lệch chuẩn

# Trung bình
mean_values <- apply(numeric_data, 2, mean)

# Độ lệch chuẩn
sd_values <- apply(numeric_data, 2, sd)

mean_values
## Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
##     5.843333     3.057333     3.758000     1.199333
sd_values
## Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
##    0.8280661    0.4358663    1.7652982    0.7622377

Lọc dữ liệu theo điều kiện

Lọc các quan sát có Sepal.Length lớn hơn giá trị trung bình.

# Trung bình Sepal.Length
mean_sepal_length <- mean(iris_data$Sepal.Length)

# Lọc dữ liệu
filtered_iris <- iris_data %>%
  filter(Sepal.Length > mean_sepal_length)

# Xem kết quả
head(filtered_iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
## 1          7.0         3.2          4.7         1.4 versicolor
## 2          6.4         3.2          4.5         1.5 versicolor
## 3          6.9         3.1          4.9         1.5 versicolor
## 4          6.5         2.8          4.6         1.5 versicolor
## 5          6.3         3.3          4.7         1.6 versicolor
## 6          6.6         2.9          4.6         1.3 versicolor

Xuất dữ liệu ra file CSV

write.csv(filtered_iris, "filtered_iris.csv", row.names = FALSE)

Kết luận