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

请求协助:基于D.IP计算各日期列的月度时间间隔

解决方案

实现步骤

  • 将原始数据中的字符型日期转换为R的Date类型
  • 以D.IP为基准,计算各日期列与它的天数间隔并加1
  • 重命名列名,同时将DIP列固定为1
  • 输出目标格式的tibble

代码实现

library(tibble)
library(dplyr)
library(lubridate)

# 原始数据
df <- tibble::tribble(
        ~Last.TP,  ~D.EndStudy,    ~EOTvisit,       ~D.END,        ~D.IP,
        "2021-02-08", "2020-08-13", "2020-08-13", "2020-08-13", "2019-07-24",
        "2021-04-19", "2021-04-26", "2021-04-26", "2021-04-26", "2020-04-06",
        "2022-01-24", "2022-02-10", "2022-02-10", "2022-02-10", "2021-01-11"
  )

# 转换日期类型并计算间隔天数(+1)
result_df <- df %>%
  mutate(across(c(Last.TP, D.EndStudy, EOTvisit, D.END, D.IP), ymd)) %>%
  mutate(
    LastTP = as.integer(Last.TP - D.IP) + 1,
    DENDSTUDY = as.integer(D.EndStudy - D.IP) + 1,
    EOTVISIT = as.integer(EOTvisit - D.IP) + 1,
    DEND = as.integer(D.END - D.IP) + 1,
    DIP = 1L
  ) %>%
  select(LastTP, DENDSTUDY, EOTVISIT, DEND, DIP)

# 查看结果
result_df

运行结果

执行代码后会输出符合要求的tibble:

# A tibble: 3 × 5
  LastTP DENDSTUDY EOTVISIT  DEND   DIP
   <int>     <int>    <int> <int> <int>
1    566       387      387   387     1
2    379       386      386   386     1
3    379       396      396   396     1

天数转月度的扩展实现

如果需要将天数转换为近似月度,可选择以下两种方式:

  • 按每月30天近似转换:
result_monthly <- result_df %>%
  mutate(across(c(LastTP, DENDSTUDY, EOTVISIT, DEND), ~ round(.x / 30, 1)))
  • 用lubridate计算精确月份差:
result_monthly_precise <- df %>%
  mutate(across(c(Last.TP, D.EndStudy, EOTvisit, D.END, D.IP), ymd)) %>%
  mutate(
    LastTP = time_length(interval(D.IP, Last.TP), "month"),
    DENDSTUDY = time_length(interval(D.IP, D.EndStudy), "month"),
    EOTVISIT = time_length(interval(D.IP, EOTvisit), "month"),
    DEND = time_length(interval(D.IP, D.END), "month"),
    DIP = 1L
  ) %>%
  select(LastTP, DENDSTUDY, EOTVISIT, DEND, DIP)

内容的提问来源于stack exchange,提问作者D. Shin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:40:35