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

使用R的group_by从小时均值计算日均时遇日期时间错误求助

问题与解决方案

问题场景

已通过R代码计算出小时均值并存储在对象avghr中,基于avghr计算日均值时触发错误:

Error in `group_by()`: ℹ In argument: `Time_sp = lubridate::floor_date(Time_sp, "1 day")`. 
Caused by error in `lubridate::floor_date()`: ! object 'Time_sp' not found

单独计算小时均值或日均值时代码可正常运行,仅在串联流程中基于avghr计算日均值时出现问题。

错误原因

日均值计算代码中,select(any_of(cn))语句使用的cn向量仅包含'Date/Time'及数值列,但avghr中的时间列名为Time_sp(而非原始数据的Date/Time),执行select后Time_sp被排除,导致后续group_by无法找到该列。

修复方案

修改日均值计算的列选择逻辑,确保保留Time_sp列,以下两种方式均可:

方式1:移除冗余的select语句

直接对avghr进行分组计算,无需额外筛选列:

# Calc daily average
avgdl <- avghr %>%
  as_tibble() %>%
  group_by(Time_sp = lubridate::floor_date(Time_sp, "1 day")) %>%
  summarise(across(where(is.numeric), ~ if(sum(is.na(.x)) > 1) NA else mean(.x, na.rm = TRUE)))

write.csv(avgdl, paste0(dirlist[idx],"_dly.csv"), row.names = FALSE)

方式2:更新cn向量包含Time_sp

若需保留select逻辑,将Time_sp加入到列选择向量中:

# 更新Required Columns,加入Time_sp
cn <- c('Time_sp', 'C1 (C1)', 'C2 (C2)', 'C5 (C5)', 'C8 (C8)', 'C11 (C11)', 'C14 (C14)')  

# Calc daily average
avgdl <- avghr %>%
  select(any_of(cn)) %>%
  as_tibble() %>%
  group_by(Time_sp = lubridate::floor_date(Time_sp, "1 day")) %>%
  summarise(across(where(is.numeric), ~ if(sum(is.na(.x)) > 1) NA else mean(.x, na.rm = TRUE)))

write.csv(avgdl, paste0(dirlist[idx],"_dly.csv"), row.names = FALSE)

补充验证

从avghr的dput输出可确认,其时间列确实为Time_sp(POSIXct类型),因此必须保证该列在日均值计算流程中被保留。

内容的提问来源于stack exchange,提问作者Alexia k Boston

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 11:22:54