R语言进阶:统计建模与数据可视化实用指南
1. Prerequisites
- Operating System: Linux (preferred), macOS, or Windows.
- Administrator/sudo privileges for software installation.
2. R/RStudio 环境配置
正确配置R语言环境是进行统计分析的基础。本节指导R和RStudio的安装及常用包的配置。
2.1 R 语言安装
以下示例针对Ubuntu 22.04 LTS系统。其他系统请参考官方文档。
sudo apt update
sudo apt install -y r-base
Expected output (truncated):
... Done.
... r-base is already the newest version (4.3.1-1.2204.0).
... 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
验证R版本:
R --version
Expected output:
R version 4.3.1 (2023-06-16) -- "Beagle Scouts"
Copyright (C) 2023 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
...
2.2 RStudio 安装
下载RStudio Desktop最新版,并进行安装。RStudio Desktop 怎么用?安装后即可启动。
# Download .deb package for Ubuntu/Debian
wget https://download1.rstudio.org/electron/jammy/amd64/rstudio-2023.09.0-463-amd64.deb
sudo dpkg -i rstudio-2023.09.0-463-amd64.deb
sudo apt install -f # Resolve dependencies
Expected output (truncated):
... Setting up rstudio (2023.09.0-463)...
... Processing triggers for mailcap (3.70+nmu1)...
2.3 常用包安装
在RStudio控制台中运行。推荐使用国内CRAN镜像,例如清华大学镜像站。
# 设置CRAN镜像
options(repos = c(CRAN = "https://mirrors.tuna.tsinghua.edu.cn/CRAN/"))
# 安装常用包
install.packages(c("tidyverse", "haven", "readxl", "ggplot2", "dplyr"))
Expected output (truncated):
... installing the source packages 'ggplot2', 'dplyr'
... DONE (tidyverse)
Note: tidyverse 包集成了 ggplot2 和 dplyr。单独安装是为了明确其重要性。
3. 统计分析:线性回归实战
本节展示如何使用R进行基本的线性回归分析。我们将使用R内置的 mtcars 数据集。
3.1 数据加载与初步探索
# 加载数据
data(mtcars)
# 查看数据结构
str(mtcars)
Expected output (truncated):
'data.frame': 32 obs. of 11 variables:
$ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
$ cyl : num 6 6 4 6 8 6 8 4 4 6 ...
...
3.2 构建线性回归模型
我们尝试预测汽车的每加仑里程 (mpg) 与马力 (hp) 和车重 (wt) 的关系。
# 构建模型
model <- lm(mpg ~ hp + wt, data = mtcars)
# 查看模型摘要
summary(model)
Expected output (truncated):
Call:
lm(formula = mpg ~ hp + wt, data = mtcars)
Residuals:
Min 1Q Median 3Q Max
-3.9408 -1.6033 -0.1983 1.3283 5.2678
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 37.22727 1.59879 23.286 < 2e-16 ***
hp -0.03177 0.01018 -3.121 0.00392 **
wt -3.87783 0.63273 -6.129 1.12e-06 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 2.55 on 29 degrees of freedom
Multiple R-squared: 0.8268, Adjusted R-squared: 0.8148
F-statistic: 69.96 on 2 and 29 DF, p-value: 9.109e-12
Warning: 线性回归模型假设数据满足特定条件(如残差正态性、同方差性)。在实际应用中,需进行模型诊断。
4. 数据可视化:ggplot2 高级应用
使用 ggplot2 进行数据可视化,提升结果的可读性。本节将创建一个散点图,并添加回归线。
4.1 散点图与回归线
# 加载ggplot2
library(ggplot2)
# 创建散点图并添加回归线
ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point(aes(color = factor(cyl))) + # 根据气缸数着色
geom_smooth(method = "lm", se = FALSE, color = "blue") + # 添加线性回归线
labs(title = "汽车马力与每加仑里程关系",
x = "马力 (hp)",
y = "每加仑里程 (mpg)",
color = "气缸数") +
theme_minimal()
Expected output: (A plot will be rendered in the RStudio Plots pane or saved if redirected.)
4.2 保存图表
将生成的图表保存为高质量图像文件。例如,保存为PNG格式。
ggsave("mpg_hp_scatter.png", width = 8, height = 6, dpi = 300)
Expected output:
Saving 8 x 6 in image
Note: ggplot2 提供了丰富的图层和主题选项,可实现高度定制化的可视化效果。更多高级用法请查阅 ggplot2 官方文档。
References:
- R Project for Statistical Computing. https://www.r-project.org/
- RStudio. https://posit.co/downloads/rstudio-desktop/
- Wickham, H. (2016). ggplot2: Elegant Graphics for Data Analysis. Springer.
- CRAN Mirrors. https://cran.r-project.org/mirrors.html