cau 1
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(ggplot2)
my_data <- iris
# 1
ket_qua_thong_ke <- my_data %>%
group_by(Species) %>%
summarise(
Trung_binh = mean(Petal.Length),
Do_lech_chuan = sd(Petal.Length),
Gia_tri_Max = max(Petal.Length)
)
print(ket_qua_thong_ke)
## # A tibble: 3 × 4
## Species Trung_binh Do_lech_chuan Gia_tri_Max
## <fct> <dbl> <dbl> <dbl>
## 1 setosa 1.46 0.174 1.9
## 2 versicolor 4.26 0.470 5.1
## 3 virginica 5.55 0.552 6.9
# 2
ggplot(data = my_data, mapping = aes(x = Species, y = Sepal.Width, fill = Species)) +
geom_violin(alpha = 0.7) +
labs(title = "Biểu đồ Violin của Sepal Width",
subtitle = "Dữ liệu: my_data (Iris)",
x = "Loài hoa",
y = "Chiều rộng đài hoa") +
theme_bw()

data(iris)
write.csv(iris, "iris.csv", row.names = FALSE)
cau 2
import pandas as pd
try:
df = pd.read_csv('iris.csv')
except FileNotFoundError:
df = pd.read_csv('iris.csv')
# 2. Tính trung bình:
# cần bỏ cột 'Species' (cột chữ)
if 'Species' in df.columns:
df_numeric = df.drop(columns=['Species'])
else:
# Nếu không tìm thấy tên cột, lệnh này tự động chỉ lấy các cột số
df_numeric = df.select_dtypes(include=['number'])
mean_val = df_numeric.mean(numeric_only=True)
mean_val.to_csv('mean_values.csv', header=['MeanValue'])
# 3. Lọc dữ liệu:
target_col = 'Petal.Width'
# Kiểm tra xem cột có tồn tại không để tránh lỗi
if target_col in df.columns:
avg_pw = df[target_col].mean()
filtered = df[df[target_col] < avg_pw]
filtered.to_csv('filtered_petal_width.csv', index=False)
# In kết quả
print("Đã xuất 2 file thành công.")
print(f"Giá trị trung bình {target_col}: {avg_pw:.2f}")
print("\nBảng trung bình:")
print(mean_val)
else:
print(f"Lỗi: Không tìm thấy cột '{target_col}'.")
print("Các cột hiện có trong file là:", df.columns.tolist())
## Đã xuất 2 file thành công.
## Giá trị trung bình Petal.Width: 1.20
##
## Bảng trung bình:
## Sepal.Length 5.843333
## Sepal.Width 3.057333
## Petal.Length 3.758000
## Petal.Width 1.199333
## dtype: float64
# Đọc file kết quả vào R
ket_qua_tb <- read.csv("mean_values.csv")
ket_qua_loc <- read.csv("filtered_petal_width.csv")
# 1. Hiển thị bảng trung bình
print("--- Bảng giá trị trung bình ---")
## [1] "--- Bảng giá trị trung bình ---"
print(ket_qua_tb)
## X MeanValue
## 1 Sepal.Length 5.843333
## 2 Sepal.Width 3.057333
## 3 Petal.Length 3.758000
## 4 Petal.Width 1.199333
# 2. Hiển thị bảng đã lọc (chỉ xem 5 dòng đầu cho gọn)
print("--- 5 dòng đầu của dữ liệu đã lọc ---")
## [1] "--- 5 dòng đầu của dữ liệu đã lọc ---"
head(ket_qua_loc)
## 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