[英]r : calculate time interval to reference
我想请求你的帮助。
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"
)
所需的临时 output 低于 tibble。 在下面的标题中,天数是参考 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)))
)
第一个答案:我们可以使用 tripple across
来做到这一点:
across
的第一行中减去全部进行D.IP
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
另一个选项使用sapply
with as.Date
来确保它是日期格式。 您可以使用以下代码:
df[] <- sapply(df, \(x) {
(as.Date(x) - as.Date("2019-07-24") + 1)/30.414
})
df
#> # A tibble: 3 × 5
#> Last.TP D.EndStudy EOTvisit D.END D.IP
#> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 18.6 12.7 12.7 12.7 0.0329
#> 2 20.9 21.1 21.1 21.1 8.48
#> 3 30.1 30.7 30.7 30.7 17.7
创建于 2023-01-20,使用reprex v2.0.2
评论中提到的@TarJae 之类的不同选项(感谢:):
df[] <- sapply(df, \(x) {
(as.Date(x) - as.Date(df$D.IP[1]) + 1)/30.414
})
df
#> # A tibble: 3 × 5
#> Last.TP D.EndStudy EOTvisit D.END D.IP
#> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 18.6 12.7 12.7 12.7 0.0329
#> 2 20.9 21.1 21.1 21.1 8.48
#> 3 30.1 30.7 30.7 30.7 17.7
创建于 2023-01-20,使用reprex v2.0.2
或者,请尝试以下代码,
df2 <- df %>% mutate(across(c('Last.TP','D.EndStudy','EOTvisit','D.END','D.IP'),
~ as.numeric((as.Date(.x, '%Y-%m-%d')-as.Date(df$D.IP,'%Y-%m-%d')+1)/30.4375),
.names = 'x{col}'))
创建于 2023-01-20,使用reprex v2.0.2
# A tibble: 3 × 10
Last.TP D.EndStudy EOTvisit D.END D.IP xLast.TP xD.EndStudy xEOTvisit xD.END xD.IP
<chr> <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 2021-02-08 2020-08-13 2020-08-13 2020-08-13 2019-07-24 18.6 12.7 12.7 12.7 0.0329
2 2021-04-19 2021-04-26 2021-04-26 2021-04-26 2020-04-06 12.5 12.7 12.7 12.7 0.0329
3 2022-01-24 2022-02-10 2022-02-10 2022-02-10 2021-01-11 12.5 13.0 13.0 13.0 0.0329
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.