1. 引言
R 语言是统计计算和数据分析领域最流行的开源工具之一,凭借丰富的包生态、强大的绘图能力和活跃的社区支持,被广泛应用于学术研究、商业分析和数据科学实践。本文通过一系列可运行的代码实例,带你从基础数据结构出发,逐步掌握数据清洗、统计分析、可视化以及建模的完整流程。
2. 环境准备与基础数据结构
在开始之前,请确保已安装 R 和 RStudio。本文所有代码均在 R 4.2 及以上版本中测试通过。首先,我们快速回顾 R 中最常用的几种数据结构。
2.1 向量与因子
# 创建数值向量 scores <- c(85, 92, 78, 96, 88) print(scores) 创建字符向量 names <- c("Alice", "Bob", "Carol", "David", "Eve") print(names) 创建因子(分类变量) gender <- factor(c("M", "F", "F", "M", "F")) print(gender) print(levels(gender))2.2 数据框的创建与查看
# 创建数据框 students <- data.frame( name = c("Alice", "Bob", "Carol", "David", "Eve"), score = c(85, 92, 78, 96, 88), gender = c("F", "M", "F", "M", "F"), stringsAsFactors = FALSE ) 查看数据结构 str(students) head(students) 访问列 students$score students[["score"]]3. 数据导入与清洗
真实世界的数据往往杂乱无章,清洗是数据分析中最耗时也最关键的一步。下面演示如何使用dplyr和tidyr完成常见的数据清洗任务。
3.1 读取 CSV 文件
# 安装并加载包 install.packages("dplyr") install.packages("tidyr") library(dplyr) library(tidyr) 读取 CSV 文件(请将路径替换为实际文件路径) df <- read.csv("data.csv", stringsAsFactors = FALSE) 为演示,我们直接创建一份模拟数据 df <- data.frame( id = 1:6, name = c("Alice", "Bob", "Carol", "David", "Eve", "Frank"), age = c(23, NA, 25, 22, NA, 24), score = c(85, 92, NA, 96, 88, 79), stringsAsFactors = FALSE ) print(df)3.2 处理缺失值
# 查看缺失值分布 colSums(is.na(df)) 删除包含缺失值的行 df_clean <- na.omit(df) 或用均值填充数值列 df_filled <- df %>% mutate( age = ifelse(is.na(age), mean(age, na.rm = TRUE), age), score = ifelse(is.na(score), mean(score, na.rm = TRUE), score) ) print(df_filled)3.3 筛选、排序与汇总
# 筛选成绩大于 85 的学生 high_scores <- df %>% filter(score > 85) print(high_scores) 按成绩降序排列 sorted <- df %>% arrange(desc(score)) print(sorted) 分组汇总:按性别计算平均分 summary_by_gender <- df %>% group_by(gender) %>% summarise( avg_score = mean(score, na.rm = TRUE), count = n() ) print(summary_by_gender)4. 数据可视化
R 的ggplot2包是数据可视化的利器,其图层化语法让复杂图表变得简洁优雅。下面演示几种最常见的图表类型。
4.1 安装并加载 ggplot2
install.packages("ggplot2") library(ggplot2) 使用内置数据集 data(mtcars) head(mtcars)4.2 散点图与回归线
# 散点图:查看油耗与马力的关系 p1 <- ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point(color = "steelblue", size = 3) + geom_smooth(method = "lm", se = FALSE, color = "red") + labs( title = "马力与油耗的关系", x = "马力 (hp)", y = "每加仑英里数 (mpg)" ) + theme_minimal() print(p1)4.3 柱状图与箱线图
# 柱状图:各气缸数的车辆数量 p2 <- ggplot(mtcars, aes(x = factor(cyl))) + geom_bar(fill = "darkgreen", alpha = 0.7) + labs( title = "气缸数分布", x = "气缸数", y = "车辆数量" ) + theme_minimal() print(p2) 箱线图:不同气缸数的油耗分布 p3 <- ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(cyl))) + geom_boxplot() + labs( title = "不同气缸数的油耗对比", x = "气缸数", y = "每加仑英里数 (mpg)" ) + theme_minimal() + theme(legend.position = "none") print(p3)4.4 保存图片
# 保存为 PNG 文件 ggsave("scatter_plot.png", plot = p1, width = 8, height = 6, dpi = 300)5. 统计分析实例
R 内置了丰富的统计函数,可以快速完成假设检验、相关分析和回归建模。
5.1 描述性统计
# 计算描述性统计量 summary(mtcars$mpg) 自定义统计函数 stats <- data.frame( mean = mean(mtcars$mpg), sd = sd(mtcars$mpg), median = median(mtcars$mpg), min = min(mtcars$mpg), max = max(mtcars$mpg) ) print(stats)5.2 t 检验与相关性分析
# 独立样本 t 检验:自动挡与手动挡的油耗差异 t_test_result <- t.test(mpg ~ am, data = mtcars) print(t_test_result) 相关性分析 cor_matrix <- cor(mtcars[, c("mpg", "hp", "wt", "disp")]) print(cor_matrix) 相关性检验 cor_test <- cor.test(mtcars$mpg, mtcars$wt) print(cor_test)5.3 线性回归建模
# 建立线性回归模型 model <- lm(mpg ~ hp + wt + cyl, data = mtcars) summary(model) 模型诊断图 par(mfrow = c(2, 2)) plot(model)6. 完整实战案例:学生成绩分析
下面把前面学到的知识串起来,完成一个完整的分析流程:从模拟数据生成、清洗、可视化到回归建模。
# ========== 完整流程 ========== library(dplyr) library(ggplot2) 1. 生成模拟数据 set.seed(42) n <- 200 study_hours <- rnorm(n, mean = 5, sd = 2) sleep_hours <- rnorm(n, mean = 7, sd = 1.5) score <- 50 + 8 * study_hours + 3 * sleep_hours + rnorm(n, 0, 5) students_data <- data.frame( study_hours = study_hours, sleep_hours = sleep_hours, score = score ) 2. 数据概览 summary(students_data) 3. 可视化:学习时间与成绩的关系 p <- ggplot(students_data, aes(x = study_hours, y = score)) + geom_point(alpha = 0.5, color = "purple") + geom_smooth(method = "lm", color = "darkblue") + labs( title = "学习时间与成绩的关系", x = "每日学习时间(小时)", y = "考试成绩" ) + theme_minimal() print(p) 4. 多元线性回归 model <- lm(score ~ study_hours + sleep_hours, data = students_data) summary(model) 5. 预测新数据 new_student <- data.frame(study_hours = 6, sleep_hours = 8) predicted_score <- predict(model, newdata = new_student) print(paste("预测成绩:", round(predicted_score, 2)))7. 总结
本文通过大量可运行的代码实例,系统展示了 R 语言在数据处理、可视化和统计分析方面的核心能力。从基础数据结构到dplyr数据清洗,从ggplot2可视化到线性回归建模,这些技能构成了 R 数据分析的基本框架。建议读者动手运行每一段代码,并尝试修改参数观察结果变化,这是掌握 R 语言最有效的方式。