You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中计算全年多站点每小时平均污染值(代码修正)

问题修正与解决方案

原代码的核心问题

  1. 日期序列生成错误:"2022-01-01":"2022-12-31"无法生成正确的日期序列,R中冒号仅适用于数值序列。
  2. 过滤逻辑缺失:filter(Stations)未指定过滤条件,无法筛选目标时段的数据。
  3. 低效循环冗余:无需按天循环,直接通过分组聚合即可实现需求。

修正后的代码(针对原始数据集)

假设原始数据集中的日期小时列名为date_hourly(需与实际列名匹配),修正代码如下:

# 加载依赖包
library(dplyr)

# 确保日期时间列格式正确
pollution_contamimants_hourly <- pollution_contamimants_hourly %>%
  mutate(date_hourly = as.POSIXct(date_hourly))

# 按小时分组,计算所有站点的平均污染值
hourly_average_pollution <- pollution_contamimants_hourly %>%
  group_by(date_hourly) %>%
  summarise(avg_pollution = mean(Pollution, na.rm = TRUE)) %>%
  ungroup()

示例数据验证

针对提供的示例数据,先修正数据读取逻辑,再执行分组计算:

library(dplyr)

# 读取并预处理示例数据
lines <- "CODI_CONTAMINANT ESTACIO ANY MES DIA_Hours Pollution date_daily 
193627 8 4 '2022-3-4' 19 31.00 '2022-03-04 19:00:00' 
45404 6 54 '2022-8-7' 24 0.20 '2022-08-08 00:00:00' 
65161 6 57 '2022-9-26' 4 0.40 '2022-09-26 04:00:00' 
308579 12 54 '2022-8-11' 22 16.00 '2022-08-11 22:00:00' 
497690 998 43 '2022-8-5' 6 4999.00 '2022-08-05 06:00:00'
402858 101 57 '2022-11-6' 3 1.98 '2022-11-06 03:00:00'"

DF <- read.table(text = lines, header = TRUE, stringsAsFactors = FALSE)

# 转换日期列为标准格式
DF <- DF %>%
  mutate(date_daily = as.POSIXct(date_daily))

# 按小时分组计算平均值
hourly_avg_example <- DF %>%
  group_by(date_daily) %>%
  summarise(avg_pollution = mean(Pollution, na.rm = TRUE)) %>%
  ungroup()

# 查看结果
print(hourly_avg_example)

示例运行结果

由于示例中每个时间戳仅对应一条记录,结果与原数据的Pollution值一致:

# A tibble: 6 × 2
  date_daily           avg_pollution
  <dttm>                       <dbl>
1 2022-03-04 19:00:00          31   
2 2022-08-05 06:00:00        4999   
3 2022-08-08 00:00:00           0.2
4 2022-08-11 22:00:00          16   
5 2022-09-26 04:00:00           0.4
6 2022-11-06 03:00:00           1.98

若实际数据中每个小时对应8条站点数据,分组后会自动计算该小时所有站点的平均值。

内容的提问来源于stack exchange,提问作者Boris Ivanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 21:41:59