r - 数一数护士在接触病人之前洗手的次数:是 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)
但这似乎不适用于管道形式,有时它们不会接触患者。任何帮助将非常感激。
解决方案
可以使用以下方法计算总独特活动:
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)
。
推荐阅读
- java - Spark找到每列的最大比例
- java - 在 intellij 项目中使用下载的 .class 文件
- java - 阴影不适用于文本视图。如何解决?
- python - 如何让 Django 模板显示 slug
- react-native - 在 Tab.Navigator React Native 中隐藏特定的 Tab.Screen
- django - 如何设计模型及其子 django
- html - 是否可以根据范围调整较少的变量?
- c++ - 如何在 Windows 上使用 cmake 配置 mysql 连接器和 boost 库?
- java - 房间数据库 - AsyncTask 未执行
- php - 我不小心删除了我的 .htaccess 文件,如何找回?