首页 > 解决方案 > 数一数护士在接触病人之前洗手的次数:是 X 在 Y 之前,group_by(ID)?

问题描述

我有一组观察到的护士进行病人护理的行为,并记录他们触摸或做的事情。这可能看起来像:

df<-data.frame(ActivityID=rep(1:3, each=3),
Action=c("Door", "Hygiene", "Patient", "Door", "Patient", "Door", "Door", "Patient", "Hygiene"))

我想检查他们是否在第一次接触患者之前为每个 ActivityID 洗手,并计算发生了多少个 ActivityID。本质上,我想知道每个活动的 X 是否发生在 Y 之前。

我的想法是使用 which 来查找 Patient 和 Hygiene 的第一次出现:

require(dplyr)
a=df%>%
group_by(ActivityID) %>%
  which(Action=="Hygiene")

b=df%>%
group_by(ActivityID) %>%
  which(Action=="Patient")

which(a<b)

但这似乎不适用于管道形式,有时它们不会接触患者。任何帮助将非常感激。

标签: rdplyr

解决方案


可以使用以下方法计算总独特活动:

library(dplyr)
total_Activities <- n_distinct(df$ActivityID)
total_Activities
#[1] 3

我们可以编写一个函数来检查在第一次接触患者之前是否洗手:

hands_washed_before_touch <- function(x) {
    ind1 <- which(x == 'Hygiene')
    ind2 <- which(x == 'Patient')
    length(ind1) && length(ind2) && ind1[1] < ind2[1]
}

并按组使用:

df1 <- df %>% 
        group_by(ActivityID) %>% 
        summarise(hands_washed = hands_washed_before_touch(Action))
df1
# ActivityID hands_washed
#       <int> <lgl>       
#1          1 TRUE        
#2          2 FALSE       
#3          3 FALSE      

要获得计数,我们可以sum hands_washed列 ie sum(df1$hands_washed)


推荐阅读