gpt4 book ai didi

R-基于引用其他行中的值的条件计算

转载 作者:行者123 更新时间:2023-12-04 23:41:58 26 4
gpt4 key购买 nike

我想引用另一行同一列中的值。我有一个带有开始和停止时刻的列。我想添加一列,指示机器是否正在运行。

这是数据的样子:

c("", "", "start", "", "", "stop", "", "", "start", "stop", "")

输出应如下所示:
 [1,] ""      ""       
[2,] "" ""
[3,] "start" "running"
[4,] "" "running"
[5,] "" "running"
[6,] "stop" "running"
[7,] "" ""
[8,] "" ""
[9,] "start" "running"
[10,] "stop" "running"
[11,] "" ""

在第二列中,我想做:
  • 如果同一行第一列等于开始 --> 正在运行
  • ELSE 如果前一行第一列等于停止 --> ""
  • ELSE 与第二列的前一行相同的值

  • 我怎样才能用 R 以优雅的方式做到这一点?

    非常感谢您的投入!

    最佳答案

    您可以使用 cumsum检查是否有比“停止”值更多的“开始”值,以了解进程是否正在运行:

    res <- cbind(myvec, c("", "running")[(cumsum(myvec=="start") > cumsum(myvec=="stop")) + 1])

    之后您可以为带有“stop”的行添加“running”:
    res[res[, 1]=="stop", 2] <- "running"

    res
    # myvec
    # [1,] "" ""
    # [2,] "" ""
    # [3,] "start" "running"
    # [4,] "" "running"
    # [5,] "" "running"
    # [6,] "stop" "running"
    # [7,] "" ""
    # [8,] "" ""
    # [9,] "start" "running"
    #[10,] "stop" "running"
    #[11,] "" ""

    数据
    myvec <- c("", "", "start", "", "", "stop", "", "", "start", "stop", "")

    关于R-基于引用其他行中的值的条件计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34656551/

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