如何使用 tidyverse 有条件地连接数据帧?

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

我感兴趣的是一个人在每个护理连续体开始时接受了多少治疗(以小时为单位)(一个人可能有多个护理连续体)。如何按照以下两个条件有条件地连接这两个数据框:

  1. 该人必须在连续开始后(或同一天)接受治疗(基本上治疗_日期 >= 连续_日期)
  2. 输出应仅包括每个人的连续体第一次预约时收到的治疗小时数(基本上是分钟(治疗_日期-连续_日期))。

人员数据框

library(tidyverse)
library(lubridate)

persons = read.csv("https://www.dropbox.com/s/5ziygvwnbvq73fc/persons.csv?dl=1") %>% 
  mutate(continuum_start = ymd(continuum_start)) %>% 
  select(-1)
persons

治疗数据框

treatments = read.csv("https://www.dropbox.com/s/0nfokiheo43lwjy/treatments.csv?dl=1") %>% 
  mutate(treatment_date = ymd(treatment_date)) %>% 
  select(-1)

treatments

r join dplyr left-join
1个回答
0
投票

也许这(或者至少这是一个好的开始):

假设

id, continuum_start
persons
中是完全唯一的:

persons %>%
  left_join(treatments, join_by(id, continuum_start <= treatment_date)) %>%
  summarize(received_hours = sum(received_hours), .by = c(id, continuum_start)) %>%
  head()
#       id continuum_start received_hours
# 1 ID1171      2011-10-14            1.0
# 2 ID1171      2013-11-22             NA
# 3   ID17      2010-02-16            3.0
# 4   ID17      2010-11-23            2.0
# 5 ID1448      2019-12-17             NA
# 6 ID1448      2018-01-04            5.5

如果

id, continuum_start
中可能存在相同
persons
的多个实例,那么我们可以通过在连接之前预先添加
mutate(rn = row_number())
来解决这个问题,然后将
rn
添加到汇总中的副字段中,ala
 .by = c(rn, id, continuum_start)

© www.soinside.com 2019 - 2024. All rights reserved.