Chapter 3 第三章 数据加工

数据加工(data wrangling)是指对原始数据集进行一系列处理,以消除数据中的错误,选择合适的变量,合并不同数据集,调整数据格式,为后续的探索性数据分析(下一章)做好准备。本章主要介绍数据清理、变量筛选、数据合成、数据塑形等数据处理操作。在学习数据处理之前,我们需要对数据与变量的类型有所了解。

学习目标

  • 📌 了解数据与变量的类型

  • 📌 掌握数据清理概念与方法

  • 📌 掌握变量筛选的方法

  • 📌 掌握长宽数据相互转换的方法

  • 📌 掌握不同数据集合并的方法

3.1 数据与变量类型

详见教程

3.1.1 数据类型

3.1.2 变量类型

3.2 数据清洁与筛选

3.2.1 数据清洁

3.2.2 变量筛选

3.3 数据塑形与整合

3.3.1 数据塑形

3.3.2 数据整合

3.4 课堂任务

任务3.1 数据类型判断

详见教程

任务3.2 变量类型判断

详见教程

任务3.3 数据清洁

# 创建含有错误值的数据
set.seed(123)  # 设置随机种子以确保可重复性

df_errors <- data.frame(Student_ID = 1:100,
                 Listening_Score = sample(-5:100, 100, replace = TRUE),
                 Speaking_Score = sample(0:103, 100, replace = TRUE),
                 Reading_Score = sample(c(0:100, NA), 100, replace = TRUE),
                 Writing_Score = sample(0:100, 100, replace = TRUE),
                 Age = sample(c(18:40, NA), 100, replace = TRUE),
                Gender = sample(c("Male", "Female"), 100, replace = TRUE))%>%
    mutate(Writing_Score  = case_when(
    Student_ID %in% c(5, 20, 50) ~ Writing_Score  + 50, # 添加异常值
    TRUE ~ Writing_Score ),
    Writing_Score  = case_when(
    Student_ID %in% c(3, 23, 54,67) ~ Writing_Score  - 50, # 添加异常值
    TRUE ~ Writing_Score ))

# 使用 drop_na() 函数删除含有缺失值的行
df_clean <- df_errors %>% drop_na()

# 使用均值插值法填补缺失值
df_interpolated <- df_errors %>%
  mutate(Reading_Score_new = ifelse(is.na(Reading_Score), 
                                 mean(Reading_Score, na.rm = TRUE), 
                                       Reading_Score))

# 使用中位数插值法填补缺失值
df_interpolated_median <- df_errors %>%
  mutate(Reading_Score_new = ifelse(is.na(Reading_Score), 
                         median(Reading_Score, na.rm = TRUE), Reading_Score))

# 使用 filter() 函数排除异常值
df_clean <- df_clean %>%
  filter(Listening_Score >= 0 & Speaking_Score <= 100 & Reading_Score <= 100)

# 过滤掉超过2个标准差的异常值
df_clean_sd <- df_errors %>%
  filter(Writing_Score >= mean(Writing_Score, na.rm = TRUE) - 2 * sd(Writing_Score, na.rm = TRUE) &
    Writing_Score <= mean(Writing_Score, na.rm = TRUE) + 2 * sd(Writing_Score, na.rm = TRUE))

# 使用四分位距法来识别并排除异常值
df_clean_iqr <- df_errors %>%
  filter(Writing_Score >= quantile(Writing_Score, 0.25, na.rm = TRUE) - 1.5 * IQR(Writing_Score, na.rm = TRUE) &
    Writing_Score <= quantile(Writing_Score, 0.75, na.rm = TRUE) + 1.5 * IQR(Writing_Score, na.rm = TRUE))

任务3.4 变量筛选

  当变量过多时,我们可以选择部分变量组成新的数据框。下面请选择所有女生的听力数据。选择所有男生的阅读数据。Filter函数主要筛选行数据,而select函数主要筛选变量即列数据。