r : calculate time interval to reference

标签 r time

我想请求您的帮助。

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"
  )

所需的临时输出低于小标题。 在下面的小标题中, 天数计算引用D.IP

(2021-02-08 - 2019-07-24) + 1 = 566 (days)
(2021/04/19 - 2020/04/06) + 1 = 379 (days)

我想低于 tibble,但需要几个月的时间。

tibble::tribble(
      ~LastTP, ~DENDSTUDY, ~EOTVISIT, ~DEND, ~DIP,
         566L,       387L,      387L,  387L,   1L,
         379L,       386L,      386L,  386L,   1L,
         379L,       396L,      396L,  396L,   1L
        )

非常感谢!

最佳答案

更新:OP请求:

library(lubridate)
library(dplyr)
df %>% 
  mutate(across(4:8, ~ . - D.IP[1])+1,
         across(4:8, ~ as.numeric(round(./30.417, digit=1)))
         )

第一个答案: 我们可以使用三重across来做到这一点:

  1. 首先,我们将字符类转换为日期类。
  2. 通过 across 进行计算,从 D.IP 的第一行中减去所有内容
  3. 我们再次在所有列中根据天数计算月份:
library(dplyr)
library(lubridate)
df %>% 
  mutate(across(, ymd),
         across(, ~ . - D.IP[1])+1,
         across(, ~ as.numeric(round(./30.417, digit=1)))
         )
 Last.TP D.EndStudy EOTvisit D.END  D.IP
    <dbl>      <dbl>    <dbl> <dbl> <dbl>
1    18.6       12.7     12.7  12.7   0  
2    20.9       21.1     21.1  21.1   8.5
3    30.1       30.7     30.7  30.7  17.7

关于r : calculate time interval to reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75186469/

相关文章:

r - 如何防止 write.csv 将 POSIXct、日期和时间类更改回字符/因子?

r - drake - 映射 ggplot 目标以输出它们

python - 您如何像 Mathematica 那样执行这种不正确的积分?

class - 删除附加有foreign/Hmisc SPSS导入功能的变量标签

r - 拟合局部级别泊松(状态空间模型)

time - 如何将一周放入日历时间层次结构中?

r - 无需循环即可将向量转换为矩阵

data-structures - 哪种数据结构的搜索和插入功能速度最快?

c - 对 strftime() 的输出结果感到困惑

ruby-on-rails - 以人类可读的格式显示持续时间,例如 "X hours, Y minutes"