gpt4 book ai didi

r - 如何正确标记组中第一个序列的结尾?

转载 作者:行者123 更新时间:2023-12-03 08:48:44 26 4
gpt4 key购买 nike

这是我正在使用的数据帧类型和所需的列输出的示例。

reprEx <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"))

Desireddf <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"),
desiredResult = c(0,0,1,1,0,0,1,0,0,1,1,1,1,1))

我正在尝试使用 dplyr 来正确标记分组 id 内的阶段更改。批准和拒绝的标记很容易,因为我只需标记第一个出现的拒绝或批准的情况:

    reprExWrong <- reprEx %>% group_by(id,stage1) %>%
mutate(desiredResult = ifelse(stage1 == last(stage1) & stage1 == "open",1,
ifelse(stage1 == first(stage1) & stage1 %in% c("approved","declined"),1,0)
)
)

问题出在开放阶段。我只想在第一个打开序列在一组 id 内结束时应用一个标志。使用我现在拥有的代码,它选择组内的最后一个打开,即使它不是第一个打开序列的一部分。例如:

reprExWrong <- data.frame(id = c(1,1,1,1,1,1,1,2,2,2,2,3,3,3),
stage1 = c("open","open","open","approved","approved","open","declined","open","open","open","declined","open","approved","declined"),
notdesiredResult = c(0,0,0,1,0,1,1,0,0,1,1,1,1,1))

在这种情况下,在 id1 内,我需要标志来显示序列在批准出现之前到达最后一个打开位置,而不是在批准出现之后打开。如果连续的打开是 id 中的第一个连续,我只需要最后一次出现打开的行中的标志。抱歉造成任何困惑,我很乐意进一步详细说明。这只是为了正确识别用于录制目的的阶段转换

最佳答案

当然有一些不那么复杂的东西,但这可能会起作用:

library(dplyr)

reprEx %>%
group_by(id) %>%
mutate(idx = cumsum(stage1 != lag(stage1, default = first(stage1))),
desiredResult = case_when(
idx != lag(idx, default = first(idx)) & stage1 != 'open' ~ 1,
lead(idx, default = last(idx)) != idx & stage1 == 'open' & idx == min(idx[stage1 == 'open']) ~ 1,
TRUE ~ 0
),
idx = NULL
)

输出:

   id   stage1 desiredResult
1 1 open 0
2 1 open 0
3 1 open 1
4 1 approved 1
5 1 approved 0
6 1 open 0
7 1 declined 1
8 2 open 0
9 2 open 0
10 2 open 1
11 2 declined 1
12 3 open 1
13 3 approved 1
14 3 declined 1

关于r - 如何正确标记组中第一个序列的结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60234120/

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