gpt4 book ai didi

r - 如何检测和标记另一列中一列的变化

转载 作者:行者123 更新时间:2023-12-04 10:13:30 25 4
gpt4 key购买 nike

我试图标记一个过程何时开始和结束。
代码需要检测更改何时开始和何时结束,并在另一列中进行标记。

示例数据:

date  process 
2007 0
2008 1
2009 1
2010 1
2011 1
2012 1
2013 0

目标:
date  process        Status
2007 0 NA
2008 1 Process_START
2009 1 NA
2010 1 NA
2011 1 NA
2012 1 Process_END
2013 0 NA

最佳答案

也许通过计算 diff并在两个方向上滞后:

dif <- diff(df1$process)
df1$Status <- factor(c(NA, dif) - 2 * c(dif, NA), levels = -3:3)
levels(df1$Status) <- c(rep(NA, 4), "Start", "End", "Start&End")
# date process Status
# 1 2007 0 <NA>
# 2 2008 1 Start
# 3 2009 1 <NA>
# 4 2010 1 <NA>
# 5 2011 1 <NA>
# 6 2012 1 End
# 7 2013 0 <NA>

更新

没有因素的版本:
dif <- diff(df1$process)
df1$Status <- c(NA, dif) - 2 * c(dif, NA)
df1$Status <- c(rep(NA,4), "Start", "End", "Start&End")[df1$Status + 4]

请注意,在单年流程的情况下,您会遇到“开始和结束”情况。

更新 2

如果系列以 process = 1 开始(或结束),则预期输出可能不是 NA 而是开始(或结束):
dif <- diff(df1$process)
df1$Status <- c(df1$process[1], dif) - 2 * c(dif, -tail(df1$process,1))
df1$Status <- c(rep(NA,4), "Start", "End", "Start&End")[df1$Status + 4]

更复杂的例子:
set.seed(4)
df1 <- data.frame(date = 2007:(2007+24), process = sample(c(0,1, 1), 25, TRUE))

最后一个版本产生:
#    date process    Status
# 1 2007 1 Start&End
# 2 2008 0 <NA>
# 3 2009 0 <NA>
# 4 2010 0 <NA>
# 5 2011 1 Start&End
# 6 2012 0 <NA>
# 7 2013 1 Start
# 8 2014 1 <NA>
# 9 2015 1 End
# 10 2016 0 <NA>
# 11 2017 1 Start&End
# 12 2018 0 <NA>
# 13 2019 0 <NA>
# 14 2020 1 Start
# 15 2021 1 <NA>
# 16 2022 1 <NA>
# 17 2023 1 <NA>
# 18 2024 1 <NA>
# 19 2025 1 <NA>
# 20 2026 1 <NA>
# 21 2027 1 <NA>
# 22 2028 1 <NA>
# 23 2029 1 <NA>
# 24 2030 1 <NA>
# 25 2031 1 End

关于r - 如何检测和标记另一列中一列的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30560843/

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