如何自动化此过程、时间间隔?

问题描述 投票:0回答:1

如何自动化这个过程?将变量“t”分为 12 天的周期,并在随访结束时分配状态,保持间隔在右侧打开,在左侧关闭。

id <- c(1,2,3)
t <- c(13, 24, 40)
status <- c(0,1,1)
df <- data.frame(id, t, status)
df
> df
  id  t status
1  1 13      0
2  2 24      1
3  3 40      1

为了获得:

id time  status
1  0-12)    0
1 [12-24)   0

2   0-12    0
2  [12-24)  0
2  [24-36)  1

3  0-12)    0
3 [12-24)   0
3 [24-36)   0
3 [36-48)   1

谢谢。

r tidyverse survival
1个回答
3
投票

tidyverse 方法可能看起来像这样。按

id
拆分数据,使用
cut
创建 12 天的间隔,最后使用
tidy::complete
添加“缺失”的数据箱:

library(dplyr, warn = FALSE)
library(tidyr)

df |>
  split(~id) |>
  lapply(\(x) {
    seq_min <- 0
    seq_max <- 12 * (max(x$t) %/% 12 + 1)
    x <- x |>
      mutate(
        time = cut(t, seq(seq_min, seq_max, 12), right = FALSE),
        .keep = "unused"
      ) |>
      tidyr::complete(id, time, fill = list(status = 0))
    x
  }) |>
  bind_rows()
#> # A tibble: 9 × 3
#>      id time    status
#>   <dbl> <fct>    <dbl>
#> 1     1 [0,12)       0
#> 2     1 [12,24)      0
#> 3     2 [0,12)       0
#> 4     2 [12,24)      0
#> 5     2 [24,36)      1
#> 6     3 [0,12)       0
#> 7     3 [12,24)      0
#> 8     3 [24,36)      0
#> 9     3 [36,48)      1
© www.soinside.com 2019 - 2024. All rights reserved.