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

R语言数据框处理:根据x1的0转1时间提取对应y1值

解决思路与代码实现

核心逻辑

要实现需求,关键是先找到每个id下x1首次从0变为1的时间点(若x1全为0则取最后一个时间点),再提取该时间点及其前一个时间点对应的y1值。我们可以用dplyr+tidyr的组合完成宽表转长表、定位关键时间点、匹配对应y1值的流程。

步骤1:构造示例数据

library(dplyr)
library(tidyr)

df <- tibble(
  id = 1:3,
  x1_t1 = c(0, 0, 0),
  x1_t2 = c(0, 0, 1),
  x1_t3 = c(0, 1, 1),
  y1_t1 = c(100, 150, 90),
  y1_t2 = c(110, 140, 150),
  y1_t3 = c(150, 180, 160)
)

步骤2:将x1和y1列转为长格式

把宽表的时间列拆分为time(时间点数字)和对应值,方便按时间顺序处理:

# 处理x1列
x_long <- df %>%
  select(id, starts_with("x1_")) %>%
  pivot_longer(cols = -id, names_to = "time", values_to = "x1") %>%
  mutate(time = as.integer(sub("x1_t", "", time)))

# 处理y1列
y_long <- df %>%
  select(id, starts_with("y1_")) %>%
  pivot_longer(cols = -id, names_to = "time", values_to = "y1") %>%
  mutate(time = as.integer(sub("y1_t", "", time)))

步骤3:定位每个id的关键时间点

找到x1首次变为1的时间点;若x1全为0,则取最后一个时间点,并计算其前一个时间点:

key_times <- x_long %>%
  group_by(id) %>%
  summarise(
    change_time = ifelse(any(x1 == 1), min(time[x1 == 1]), max(time))
  ) %>%
  mutate(before_time = change_time - 1)

步骤4:匹配对应y1值并整理结果

将关键时间点与y1的长表连接,提取前后时间点的y1值:

result <- key_times %>%
  left_join(y_long, by = c("id", "before_time" = "time")) %>%
  rename(y1_before = y1) %>%
  left_join(y_long, by = c("id", "change_time" = "time")) %>%
  rename(y1_after = y1) %>%
  select(id, y1_before, y1_after)

# 输出结果
result
#> # A tibble: 3 × 3
#>      id y1_before y1_after
#>   <int>     <dbl>    <dbl>
#> 1     1       110      150
#> 2     2       140      180
#> 3     3        90      150

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 09:24:52