在 R 中,如果满足条件(等于 1),是否可以提取每个 ID 最早日期的行,如果不满足条件,则提取最晚日期?

In R is there a way to extract the row with the earliest date per ID if it meets a condition (is equal to 1) and the latest date if it does not?

抱歉,如果之前有人问过这个问题,但我在这里找不到解决方案。在 R 中,我想在给定条件的最早数据点上按 ID 过滤我的数据集,如果没有则在最新数据点上过滤。

因此,根据这个数据集查看个人是否做出了回应:

    ID   response   follow_up_date
    P1  0   2001-01-01
    P1  0   2002-01-01
    P1  0   2003-01-01
    P2  0   2003-01-01
    P2  1   2004-01-01
    P3  1   2001-01-01
    P3  1   2003-01-01
    P3  1   2004-01-01

我想提取每个 ID 中有人回复的最早日期 (response=1) 的行,如果他们还没有回复 (response = 0),我想提取最后一个 ID 的行随访日期。所以输出应该是:

     ID   response  follow_up_date
     P1 0   2003-01-01
     P2 1   2004-01-01 
     P3 1   2001-01-01

有谁知道我将如何实现这一目标?我假设有一种使用 dplyrdata.table 的方法,但我还没有完全弄明白。

创建数据框的代码在这里:

ID<-c("P1","P1","P1","P2","P2","P3","P3","P3")
response<-c(0,0,0,0,1,1,1,1)
follow_up_date<-as.Date(c("2001-01-01","2002-01-01","2003-01-01","2003-01-01","2004-01-01","2001-01-01","2003-01-01","2004-01-01"))
df<-data.frame(ID,response,follow_up_date)

您必须使用 %>% 运算符和 summarise()。如果 sum 为 0 或 1 在其他情况下,我将自己的函数设为 return 0。如果您知道将数字转换为二进制的更好方法,欢迎您。这是一个例子:

binary_sum <- function (data) {
    s <- sum(data)
    if (s == 0) {
       return(0)
    } else {
       return(1)
    }
}

df %>% group_by(ID) %>% summarise(response = binary_sum(response), follow_up_date = max(follow_up_date))
 
df %>% 
  group_by(ID) %>% # group by ID
  mutate(index = case_when(response == 1 ~ which.min(follow_up_date),  # get earliest date if response == 0
                           response == 0 ~ which.max(follow_up_date))) %>% # get latest date if reponse == 1
  slice(first(index)) %>% # get first occurance of index
  select(-index)

或与data.table

library(data.table)
setDT(df)
df[df[,.I[ifelse(response[1] == 0,which.max(follow_up_date),which.min(follow_up_date))],by = ID]$V1]