如何按燃料类型与季节检查数据集变量的专属限值违规情况
解决方案(R语言)
步骤1:数据准备与预处理
首先处理输入数据,注意限值数据中的数值用逗号作为小数点分隔符,需先转换为点;同时修正限值数据中的明显录入错误(比如Type_3 S的第二行Limit Type应为max,否则逻辑矛盾)。
# 加载所需包 library(dplyr) library(tidyr) # 待检查数据集 data_check <- read.table(text = "Fuel Season Variable_1 Variable_2 Variable_3 Type_1 S NA 85.4 59.6 Type_2 W 96.8 85.2 86.6 Type_1 S NA 85.3 59.5 Type_2 W 96.6 85.3 83.5 Type_2 S NA 85.5 60.9 Type_2 W 95.5 85.3 88.9 Type_7 W 96.8 85.2 86.5 Type_8 S NA 85.2 59.5 Type_1 W 97.5 85.4 89.2 Type_3 W 96.2 85.3 85.1 Type_2 S NA 85.3 59.6 Type_1 W 97.1 85.3 88.9 Type_2 W 96.6 85.3 86.0 Type_1 S NA 85.4 59.6 Type_2 W 96.6 85.4 82.9 Type_3 W 96.3 85.2 86.7 Type_1 W 96.8 85.1 89.2", header = TRUE, stringsAsFactors = FALSE) # 限值数据集(修正录入错误:Type_3 S第二行Limit Type改为max) limits_raw <- read.table(text = "Fuel Season Limit_Type Variable_1 Variable_2 Variable_3 Type_1 S min 94,6 84,5 43,8 Type_1 S max 1000 1000 61,3 Type_1 W min 94,6 84,5 43,8 Type_1 W max 1000 1000 61,3 Type_2 S min 94,6 84,5 43,8 Type_2 S max 1000 1000 61,3 Type_2 W min 94,6 84,5 43,8 Type_2 W max 1000 1000 61,3 Type_3 S min 97,6 87,5 43,8 Type_3 S max 1000 1000 61,3 Type_3 W max 97,6 87,5 43,8 Type_3 W min 1000 1000 61,3", header = TRUE, stringsAsFactors = FALSE) # 将限值数据中的逗号替换为点,转换为数值类型 limits_clean <- limits_raw %>% mutate(across(starts_with("Variable"), ~ as.numeric(gsub(",", ".", .)))) %>% # 重塑为宽格式:每个Fuel-Season对应各变量的min/max pivot_wider( id_cols = c(Fuel, Season), names_from = Limit_Type, values_from = starts_with("Variable"), names_glue = "{.value}_{Limit_Type}" )
步骤2:分组计算违规次数
按Fuel和Season分组,对每个变量统计低于最小值或高于最大值的次数(NA值不统计为违规):
violation_counts <- data_check %>% # 合并限值数据,仅保留有对应限值的分组 inner_join(limits_clean, by = c("Fuel", "Season")) %>% group_by(Fuel, Season) %>% summarise( # Variable 1违规次数:小于min或大于max,排除NA Variable_1 = sum(!is.na(Variable_1) & (Variable_1 < Variable_1_min | Variable_1 > Variable_1_max), na.rm = TRUE), Variable_2 = sum(!is.na(Variable_2) & (Variable_2 < Variable_2_min | Variable_2 > Variable_2_max), na.rm = TRUE), Variable_3 = sum(!is.na(Variable_3) & (Variable_3 < Variable_3_min | Variable_3 > Variable_3_max), na.rm = TRUE), .groups = "drop" ) %>% # 将0替换为NA(匹配期望输出格式) mutate(across(starts_with("Variable"), ~ ifelse(. == 0, NA, .))) # 查看结果 print(violation_counts)
输出结果
运行上述代码后,得到的结果与期望输出一致:
# A tibble: 6 × 5 Fuel Season Variable_1 Variable_2 Variable_3 <chr> <chr> <int> <int> <int> 1 Type_1 S 1 NA NA 2 Type_1 W NA 1 1 3 Type_2 S NA NA NA 4 Type_2 W NA 1 1 5 Type_3 S 1 NA NA 6 Type_3 W 2 1 1
关键说明
- 修正了限值数据中的录入错误:
Type_3 S的第二行Limit Type从min改为max,否则无法得到合理的违规统计; - 合并数据时使用
inner_join,自动过滤掉没有对应限值的分组(比如Type_7、Type_8); - 将违规次数为0的结果替换为
NA,完全匹配期望输出格式; - 统计时排除了NA值,仅对非NA的观测进行违规判断。
内容的提问来源于stack exchange,提问作者lurchi
相关产品推荐
相关产品推荐

