创建一个变量,指示目标日期是否在两个日期之间,但每个案例有几行

问题描述 投票:0回答:1

我正在尝试创建一个名为 positive 的新变量,它指示 targ_date 介于 st_dateen_date 之间的日期范围,但每个 ID 有几行。我正在尝试创建类似变量 Positive 的东西。例如,如果在某个日期范围内,目标日期在其中,则该日期范围应分配为 1,否则分配为 0。这是重现我需要的代码。

ID<-c("4674","4674","4674","4674","4674","4674","4674",   "25694","25694","25694","25694","25694","25694","25694", "92252","92252","92252","92252","92252") 

st_date<-c(NA,NA,"2022-05-09",NA,NA,"2013-07-01","2013-11-27", NA,NA,NA,NA,NA,"2011-04-14","2011-08-04", NA,NA,"2015-08-07","2017-08-18",NA) 

en_date<-c(NA,NA,"2022-06-10",NA,NA,"2013-08-01","2013-12-27", NA,NA,NA,NA,NA,"2011-06-13","2011-08-15", NA,NA,"2015-09-09","2017-09-18",NA) 

targ_date<-c("2022-05-15","2013-05-01",NA,NA,NA,"2013-06-30",NA, NA,NA,NA,NA,NA,"2011-06-13","2011-07-15", NA,NA,"2015-08-20","2017-08-23",NA) 

positive<-c(0,0,1,0,0,0,0, 0,0,0,0,0,1,0, 0,0,1,0,0) 

data<-data.frame(ID,st_date,en_date,targ_date,positive)

我已经尝试过:

ds <- ds %>% 
group_by(ID) %>% 
mutate( between_any = as.numeric(inrange(targ_date, st_date, en_date)) ) %>% 
ungroup() 

但它没有达到我想要的效果。

r date variables group-by
1个回答
0
投票

希望 dpllyer 中的函数之间就是您正在寻找的:

library(dplyr)
ds <- data %>% rowwise() %>%
  group_by(ID) %>% 
  mutate(between_any = between(targ_date, st_date, en_date)) %>% 
  mutate(between_any = as.integer(replace_na(between_any,0))) %>%
  ungroup() 
© www.soinside.com 2019 - 2024. All rights reserved.