Bootstrap

【R语言】需求2:从csv文件读取成绩并统计各科成绩均分,标准差

学习测试代码

# 完成需求  4,5,6


# 代码正文内容
# 加载必要的库
# 确保已安装并加载了ggplot2包
if (!require(ggplot2)) install.packages("ggplot2")
if (!require(readr)) install.packages("readr")

library(ggplot2)
library(readr)


# 从CSV文件中读取数据
df <- read_csv("C:/Users/Administrator/Desktop/王国炜数据.csv")

# 计算每门科目的平均分和标准差
mean_math <- mean(df$Math)
sd_math <- sd(df$Math)
mean_english <- mean(df$English)
sd_english <- sd(df$English)
mean_statistics <- mean(df$Statistics)
sd_statistics <- sd(df$Statistics)

# 打印每门科目的平均分和标准差
cat("Mean and Standard Deviation for each subject:\n")
cat("Math: Mean =", mean_math, ", SD =", sd_math, "\n")
cat("English: Mean =", mean_english, ", SD =", sd_english, "\n")
cat("Statistics: Mean =", mean_statistics, ", SD =", sd_statistics, "\n\n")

# 查找每门科目的最高分和最低分及对应的学生ID
max_math <- max(df$Math)
min_math <- min(df$Math)
student_max_math <- df$StudentID[which.max(df$Math)]
student_min_math <- df$StudentID[which.min(df$Math)]

max_english <- max(df$English)
min_english <- min(df$English)
student_max_english <- df$StudentID[which.max(df$English)]
student_min_english <- df$StudentID[which.min(df$English)]

max_statistics <- max(df$Statistics)
min_statistics <- min(df$Statistics)
student_max_statistics <- df$StudentID[which.max(df$Statistics)]
student_min_statistics <- df$StudentID[which.min(df$Statistics)]

# 打印每门科目的最高分和最低分及对应的学生ID
cat("Highest and Lowest Scores for each subject with Student IDs:\n")
cat("Math: Max =", max_math, "by", student_max_math, ", Min =", min_math, "by", student_min_math, "\n")
cat("English: Max =", max_english, "by", student_max_english, ", Min =", min_english, "by", student_min_english, "\n")
cat("Statistics: Max =", max_statistics, "by", student_max_statistics, ", Min =", min_statistics, "by", student_min_statistics, "\n\n")

# 计算每位同学的总分并按总分由高到低排序
df$TotalScore <- rowSums(df[, c("Math", "English", "Statistics")])
sorted_students <- df[order(-df$TotalScore), ]

# 打印按总分由高到低排序的学生ID
cat("Student IDs sorted by total score from high to low:\n")
print(sorted_students$StudentID)


# 为每门科目和总分绘制直方图
ggplot(df, aes(x=Math)) + geom_histogram(binwidth=5, fill="blue", color="black") + ggtitle("Histogram of Math Scores")
;