我有一个数据框( data ),看起来像这样。COVID测试数据帧:
> ID DATE Result
1 1/11/2020 POSITIVE
2 1/11/2020 NEGATIVE
2 2/11/2020 POSITIVE
3 2/11/2020 POSITIVE
3 3/11/2020 NEGATIVE然后我有了另一个数据框(data_new),它看起来像这样,这只是积极的结果
> ID DATE Result
1 1/11/2020 POSITIVE
2 2/11/2020 POSITIVE
3 2/11/2020 POSITIVE原始数据集非常大。我的愿望是找到一个代码,它将接受"data_new“,并回顾”数据“,以找出相同的ID是否出现在”数据“中,并在结果为阳性的日期之前进行了测试。
这有可能吗?
发布于 2020-11-02 22:40:08
这样做是可行的:
library(dplyr)
library(tidyr)
df2 %>% left_join(df1, by = 'ID') %>% filter((DATE.x > DATE.y) & Result.x == 'POSITIVE')
# A tibble: 1 x 5
ID DATE.x Result.x DATE.y Result.y
<dbl> <date> <chr> <date> <chr>
1 2 2020-11-02 POSITIVE 2020-11-01 NEGATIVE使用的数据:
df1
# A tibble: 5 x 3
ID DATE Result
<dbl> <date> <chr>
1 1 2020-11-01 POSITIVE
2 2 2020-11-01 NEGATIVE
3 2 2020-11-02 POSITIVE
4 3 2020-11-02 POSITIVE
5 3 2020-11-03 NEGATIVE
df2
# A tibble: 3 x 3
ID DATE Result
<dbl> <date> <chr>
1 1 2020-11-01 POSITIVE
2 2 2020-11-02 POSITIVE
3 3 2020-11-02 POSITIVE发布于 2020-11-02 22:43:15
由于您有相似的列名,因此我建议在连接数据之前重命名列名。对于每个ID,您可以检查他们是否在阳性结果日期之前进行了测试。
library(dplyr)
df1 %>%
rename(test_date = DATE) %>%
left_join(df2 %>%
rename(positive_date = DATE, final_result = Result), by = 'ID') %>%
mutate(across(c(test_date, positive_date), lubridate::dmy)) %>%
group_by(ID) %>%
summarise(test_before = any(first(positive_date) > test_date))
# ID test_before
# <int> <lgl>
#1 1 FALSE
#2 2 TRUE
#3 3 FALSE https://stackoverflow.com/questions/64647457
复制相似问题