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

将时间间隔转为单小时行:R语言气象数据格式转换需求

将YR气象预报数据展开为逐小时格式

方法一:使用tidyverse工具包

这种方法代码简洁易读,适合快速处理数据:

  1. 加载依赖包
library(tidyverse)
  1. 读取原始数据
df1 <- read.table(text = "time temperature
00 0
01 0
02 1
03 1
04 2
05 2
06 2
07-13 3
13-19 4
19-01 1", header = TRUE)
  1. 处理并展开数据
df1.full <- df1 %>%
  # 拆分时间列,单个小时的行自动补全结束时间
  separate(time, c("start", "end"), sep = "-", fill = "right") %>%
  # 转换为数值类型,补全空的结束时间
  mutate(across(c(start, end), as.numeric),
         end = ifelse(is.na(end), start, end)) %>%
  rowwise() %>%
  # 生成对应小时序列:跨天区间只保留当天19-23的部分
  mutate(time = list(if (start <= end) seq(start, end) else seq(start, 23))) %>%
  # 展开列表为单行
  unnest(time) %>%
  # 整理列格式,可选将时间转为两位数字
  select(time, temperature) %>%
  ungroup() %>%
  mutate(time = sprintf("%02d", time))

查看结果:

df1.full

输出:

time temperature
1    00           0
2    01           0
3    02           1
4    03           1
5    04           2
6    05           2
7    06           2
8    07           3
9    08           3
10   09           3
11   10           3
12   11           3
13   12           3
14   13           4
15   14           4
16   15           4
17   16           4
18   17           4
19   18           4
20   19           1
21   20           1
22   21           1
23   22           1
24   23           1

方法二:基础R实现(无需额外包)

如果不想加载第三方包,用基础R也能完成:

df1 <- read.table(text = "time temperature
00 0
01 0
02 1
03 1
04 2
05 2
06 2
07-13 3
13-19 4
19-01 1", header = TRUE)

result_list <- list()

for (i in seq(nrow(df1))) {
  time_split <- strsplit(df1$time[i], "-")[[1]]
  start <- as.numeric(time_split[1])
  temp <- df1$temperature[i]
  
  if (length(time_split) == 1) {
    hours <- start
  } else {
    end <- as.numeric(time_split[2])
    hours <- if (start <= end) seq(start, end) else seq(start, 23)
  }
  
  result_list[[i]] <- data.frame(time = sprintf("%02d", hours), temperature = temp)
}

df1.full <- do.call(rbind, result_list)
rownames(df1.full) <- NULL

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 16:23:19