R-基于对其他行

时间:2016-01-07 13:37:26

标签: r if-statement reference

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

这就是数据的样子:

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与第二列的上一行相同的值

如何以优雅的方式使用R?

非常感谢您提前输入!

2 个答案:

答案 0 :(得分:6)

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

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

您可以为之后添加“停止”的行添加“正在运行”:

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", "")

答案 1 :(得分:1)

我确信这不是最优雅的方式,但不知怎的,我觉得它给你想要的东西。您可以使用for-loop

x <- c("", "", "start", "", "", "stop", "", "", "start", "stop", "")
flag <- 0
y <- array()

for(i in 1:length(x))
{
  if(flag == 0 & x[i] == "")
  y[i] <- ""
  else if(x[i] == "start" | x[i] == "")
  {
   flag = 1;
   y[i] <- "running"
  } 
  else if(x[i] == "stop")
  {
   y[i] <- "running"
   flag <- 0
  }
}

<强>输出

y
#[1] ""        ""        "running" "running" "running" "running" ""        ""        "running"
#[10] "running" ""