我有兩個資料集,其中包含許多患者的tests(日期和結果 - 長格式)和meds(用藥日期)。每位患者在兩個不同的日期進行兩次測驗。
(tests <- structure(list(id = c(1, 1, 2, 2, 3, 3), test_date = structure(c(10957,
10963, 11001, 11035, 11091, 11230), class = "Date"), test_result = c(1,
1, 0, 1, 0, 0)), row.names = c(NA, -6L), class = "data.frame"))
#> id test_date test_result
#> 1 1 2000-01-01 1
#> 2 1 2000-01-07 1
#> 3 2 2000-02-14 0
#> 4 2 2000-03-19 1
#> 5 3 2000-05-14 0
#> 6 3 2000-09-30 0
(meds <- structure(list(id = c(1, 2, 3), med_date = structure(c(10959,
10956, NA), class = "Date")), row.names = c(NA, -3L), class = "data.frame"))
#> id med_date
#> 1 1 2000-01-03
#> 2 2 1999-12-31
#> 3 3 <NA>
我正在嘗試創建一個新列tests,指定該患者是否在兩個測驗日期之間的間隔內接受了藥物治療。
預期輸出:
#> id test_date test_result received_med_within
#> 1 1 2000-01-01 1 TRUE
#> 2 1 2000-01-07 1 TRUE
#> 3 2 2000-02-14 0 FALSE
#> 4 2 2000-03-19 1 FALSE
#> 5 3 2000-05-14 0 FALSE
#> 6 3 2000-09-30 0 FALSE
我以為我可以解決這個問題
- 轉向
tests更廣泛, left_join喜歡meds它,- 使用
if_else(med_date %within% interval(test_date_1, test_date_2), TRUE, FALSE) - 再次轉動它更長的時間
然而,這是相當復雜的,因為真實的資料集包含更多的列,旋轉可能會有點棘手。
有沒有更簡潔的方法來檢查日期是否介于長資料集中的兩個日期之間?
uj5u.com熱心網友回復:
您可以執行以下操作:
library(dplyr)
tests %>%
left_join(meds) %>%
group_by(id) %>%
mutate(received_med_within = between(med_date, test_date[1], test_date[2])) %>%
tidyr::replace_na(list(received_med_within = FALSE)) %>%
dplyr::select(-4)
# A tibble: 6 x 4
# Groups: id [3]
# id test_date test_result received_med_within
# <dbl> <date> <dbl> <lgl>
# 1 1 2000-01-01 1 TRUE
# 2 1 2000-01-07 1 TRUE
# 3 2 2000-02-14 0 FALSE
# 4 2 2000-03-19 1 FALSE
# 5 3 2000-05-14 0 FALSE
# 6 3 2000-09-30 0 FALSE
uj5u.com熱心網友回復:
您可以嘗試使用match.
tests <- tests[order(tests$id, tests$test_date),] #In case its not ordered
i <- match(tests$id[c(TRUE, FALSE)], meds$id)
cbind(tests, received_med_within =
rep(tests$test_date[c(TRUE, FALSE)] < meds$med_date[i] &
meds$med_date[i] < tests$test_date[c(FALSE, TRUE)], each = 2))
# id test_date test_result received_med_within
#1 1 2000-01-01 1 TRUE
#2 1 2000-01-07 1 TRUE
#3 2 2000-02-14 0 FALSE
#4 2 2000-03-19 1 FALSE
#5 3 2000-05-14 0 NA
#6 3 2000-09-30 0 NA
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/496819.html
上一篇:如何防止遞回方法更改變數的值?
下一篇:在Excel中重復日期序列
