# R script: Câu 1 — Tính độ lệch chuẩn Sepal.Length theo Species và vẽ violin Petal.Width
# 1) Cài (nếu cần) & nạp ggplot2
if (!requireNamespace("ggplot2", quietly = TRUE)) install.packages("ggplot2")
library(ggplot2)
# 2) Tính độ lệch chuẩn của Sepal.Length theo Species
sd_table <- aggregate(Sepal.Length ~ Species, data = iris, FUN = sd)
write.csv(iris, "iris.csv", row.names = FALSE)
print(sd_table)
## Species Sepal.Length
## 1 setosa 0.3524897
## 2 versicolor 0.5161711
## 3 virginica 0.6358796
# 3) Vẽ biểu đồ violin của Petal.Width theo Species
p <- ggplot(iris, aes(x = Species, y = Petal.Width)) +
geom_violin(trim = FALSE) +
geom_jitter(width = 0.15, size = 1, alpha = 0.6) +
labs(
title = "Violin plot: Petal.Width theo Species",
x = "Species",
y = "Petal.Width"
) +
theme_minimal()
print(p)

# 4) Lưu ảnh (tùy chọn)
ggsave("violin_petal_width_by_species.png", plot = p, width = 6, height = 4, dpi = 150)
# Câu 2 - Pandas: đọc iris.csv, lọc Sepal.Width < 3.0, xuất filtered_width.csv
import pandas as pd
# 1) Đọc file (đặt iris.csv cùng thư mục với file chạy)
df = pd.read_csv("iris.csv")
# 2) Kiểm tra có cột Sepal.Width không (nếu tên khác, sửa ở đây)
if "Sepal.Width" not in df.columns:
raise ValueError("Không tìm thấy cột 'Sepal.Width' trong iris.csv. Kiểm tra tên cột.")
# 3) Lọc
filtered = df[df["Sepal.Width"] < 3.0]
# 4) Ghi file kết quả
filtered.to_csv("filtered_width.csv", index=False)
# 5) In vài thông tin để kiểm tra
print(f"Số dòng ban đầu: {len(df)}")
## Số dòng ban đầu: 150
print(f"Số dòng sau khi lọc (Sepal.Width < 3.0): {len(filtered)}")
## Số dòng sau khi lọc (Sepal.Width < 3.0): 57
print("5 dòng đầu của kết quả:")
## 5 dòng đầu của kết quả:
print(filtered.head())
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 8 4.4 2.9 1.4 0.2 setosa
## 41 4.5 2.3 1.3 0.3 setosa
## 53 5.5 2.3 4.0 1.3 versicolor
## 54 6.5 2.8 4.6 1.5 versicolor
## 55 5.7 2.8 4.5 1.3 versicolor