簡體   English   中英

使用警告按組計算兩個日期之間的差異

[英]Calculating the difference between two dates by group with caveat

數據如下所示:

df <- data.frame(
  id = c(283,994,294,294,1001,1001), 
  stint = c(1,1,1,2,1,2), 
  admit = c("2010-2-3","2011-2-4","2011-3-4","2012-4-1","2016-1-2","2017-2-3"),
  release = c("2011-2-3","2011-2-28","2011-4-1","2014-6-6","2017-2-1","2018-3-1")
)

好吧,請多多包涵,因為我發現這種語言很難表達。 我需要通過 id 計算第一階段的發布日期和第二階段的錄取日期之間的差異。 所以對於上面的示例,我稱之為“曝光”的差異應該是這樣的

exposure=c(NA,NA,365,NA,2,NA)

因此,如果只有 1 次,將返回 NA,如果有超過 1 次,則曝光期將使用之前的發布日期和當前的錄取日期來計算。 因此,第 3 階段的曝光將被承認為第 3 階段 - 第 2 階段的釋放。

這是dplyr方法。 我們將找到stint為 2 (1) 的admit ( release ) 的值,取其差,並用每組id的值替換 exposure 的第一個條目。

library(dplyr)

df %>% 
  mutate(
    across(c(admit, release), as.Date), 
    exposure = NA_integer_
  ) %>% 
  group_by(id) %>% 
  mutate(exposure = replace(
    exposure, 1L, 
    as.integer(admit[match(2, stint)] - release[match(1, stint)])
  ))
  

Output

# A tibble: 6 x 5
# Groups:   id [4]
     id stint admit      release    exposure
  <dbl> <dbl> <date>     <date>        <int>
1   283     1 2010-02-03 2011-02-03       NA
2   994     1 2011-02-04 2011-02-28       NA
3   294     1 2011-03-04 2011-04-01      366
4   294     2 2012-04-01 2014-06-06       NA
5  1001     1 2016-01-02 2017-02-01        2
6  1001     2 2017-02-03 2018-03-01       NA

如果 stint == 2,您要計算曝光,否則返回 NA。 這可以通過 ifelse 來實現。 但是,您希望該版本來自之前的發布日期。 這可以通過滯后來完成。 但這會將暴露值與暴露 ==2 的承認聯系起來,而您希望暴露與計算中使用的先前版本相關聯。 因此,刪除第一個曝光值並在最后添加一個 NA。

  df %>% 
    mutate(across(c(admit, release), as.Date), 
           exposure = c(ifelse(stint == 2, admit - lag(release), NA)[-1], NA))

哪個產量

    id stint      admit    release exposure
1  283     1 2010-02-03 2011-02-03       NA
2  994     1 2011-02-04 2011-02-28       NA
3  294     1 2011-03-04 2011-04-01      366
4  294     2 2012-04-01 2014-06-06       NA
5 1001     1 2016-01-02 2017-02-01        2
6 1001     2 2017-02-03 2018-03-01       NA

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM