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

R语言:如何将指定时间点设为0,前后行分别设为递减、递增整数?

解决方案

核心思路

先为每个唯一时间点分配相对目标时间的偏移值,再将该偏移值批量赋值给对应时间点的所有行,即可实现目标时间点为0、之前行递减、之后行递增的需求。

具体实现代码

# 原始数据集
Time = c("2023-07-28 22:14:00", "2023-07-28 22:15:00", "2023-07-28 22:16:00", "2023-07-28 22:17:00", "2023-07-28 22:18:00")
num = c(1000,1200,1234,980,1300)
df <- data.frame(Time = rep(Time, num), num = sequence(num))    
df[paste0('rand', seq_along(Time))] <- rnorm(length(Time) * sum(num))

# 定义目标时间
target_time <- "2023-07-28 22:16:00"

# 获取排序后的唯一时间序列(确保时间顺序正确)
unique_times <- sort(unique(df$Time))

# 定位目标时间在序列中的位置
target_pos <- which(unique_times == target_time)

# 创建时间到偏移值的映射:偏移值 = 时间索引 - 目标索引
time_offset_map <- setNames(seq_along(unique_times) - target_pos, unique_times)

# 为原数据框添加偏移列
df$time_offset <- time_offset_map[df$Time]

# 查看结果示例
head(df)
tail(df)

代码说明

  • unique_times <- sort(unique(df$Time)):提取并排序所有唯一时间点,确保时间顺序逻辑正确(即使原始数据时间乱序也能适配)。
  • target_pos <- which(unique_times == target_time):找到目标时间在排序后序列中的位置索引。
  • time_offset_map <- setNames(seq_along(unique_times) - target_pos, unique_times):生成每个时间点对应的偏移值——目标时间的偏移为0,之前的时间索引小于目标索引,偏移值为负数(如22:15对应-1、22:14对应-2);之后的时间索引大于目标索引,偏移值为正数(如22:17对应+1、22:18对应+2)。
  • df$time_offset <- time_offset_map[df$Time]:通过映射关系,将偏移值批量赋值给原数据框的每一行,同一个时间点的所有行将获得相同的偏移值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 03:05:21