gpt4 book ai didi

r - 如何通过变量创建新列?

转载 作者:行者123 更新时间:2023-12-02 17:24:41 25 4
gpt4 key购买 nike

我的数据包括每个 ID 上不同人 ( Day ) 的数据一周中的时间以及他们在医院不同区域度过的时间或Ward 。这次给我的时间是分钟:秒或 Duration 。我的数据示例是:

ShiftData <- data.frame(ID = c("Nelson", "Nelson", "Nelson", "Nelson", "Nelson", 
"Justin", "Justin", "Justin", "Justin", "Justin",
"Nelson", "Nelson", "Nelson", "Nelson", "Nelson",
"Justin", "Justin", "Justin", "Justin", "Justin"),
Day = c("Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday",
"Tuesday", "Tuesday", "Tuesday", "Tuesday", "Tuesday",
"Tuesday", "Tuesday", "Tuesday", "Tuesday", "Tuesday"),
Ward = c("Gen", "Anaesth", "Front Desk", "PreOp", "Front Desk",
"PreOp", "Front Desk", "Anaesth", "Front Desk", "Gen",
"Gen", "Anaesth", "PreOp", "Front Desk", "Gen",
"Front Desk", "PreOp", "PostOp", "Front Desk", "Anaesth"),
Duration = c("5:35", "4:08", "4:30", "6:33", "4:17",
"15:35", "4:28", "9:37", "18:33", "4:20",
"9:45", "8:28", "6:37", "2:34", "4:27",
"19:35", "4:20", "9:47", "11:33", "4:26"))

我首先希望包括一列,指示每个ID何时正在轮换或轮类。一个"Front Desk"Ward列表明一个人何时改变他们的轮类。一个人可以从 "Front Desk" 开始,根据他们前一天工作的小时数进行调节(当前分析不需要此计算)。我的预期输出是 是:

ShiftData$Shift <- c(1,1,0,2,0,
1,0,2,0,3,
1,1,1,0,2,
0,1,1,0,2)

我的问题类似于this question除非有 "Front Desk"我想要一个 0 和之后的任何事件,按顺序向上计数。

我该如何创建这个?

我知道我可以为 "Front Desk" 添加 0使用:

ShiftData$Shift <- ifelse(ShiftData$Ward=='Front Desk', 0, NA)

但我不确定如何为该列的每个其他部分添加顺序计数?

最佳答案

这个问题可以用dplyr解决:

ShiftData$Shift <- (ShiftData %>%
group_by(ID,Day) %>%
mutate(tmp = ifelse(Ward=="Front Desk",1,0), #tag to sum front desk shifts
tmp2 = cumsum(tmp), #cumsum shows shifts in a day
Ward1 = Ward[1], #this and the below count your first shift if you didn't start on desk duty
shift = ifelse(Ward1=="Front Desk",tmp2,tmp2+1))
)$shift
ShiftData$Shift[ShiftData$Ward=="Front Desk"] <- 0

关于r - 如何通过变量创建新列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43027297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com