简体   繁体   English

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

[英]R- Conditional calculation based on reference to values in other row

I would like to make a reference to a value in the same column on another row. 我想在另一行的同一列中引用一个值。 I have one column with start and stop moment. 我有一栏有开始和停止时刻。 I would like to add a column that indicates if the machine is running or not. 我想添加一个列,指示机器是否正在运行。

This is how the data looks like: 这是数据的样子:

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

The output should look like this: 输出应如下所示:

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

In the second column I would like to do: 在第二栏中我想做:

  • IF same row first column equals start --> running 如果同一行第一列等于开始 - >运行
  • ELSE IF previous row first column equals stop --> "" 如果前一行第一列等于停止 - >“”
  • ELSE the same value as the previous row for the second column ELSE与第二列的前一行的值相同

How can I do this in an elegant way with R? 我怎么能用R优雅地做到这一点?

Thank you very much on beforehand for your input! 非常感谢您提前输入!

You can use cumsum to check wether there are more "start" values than "stop" values to know if the process is running or not: 您可以使用cumsum来检查是否存在比“stop”值更多的“start”值以了解进程是否正在运行:

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

you can add "running" for lines with "stop" afterwards: 之后可以为“停止”的行添加“运行”:

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

data 数据

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

I am sure this is not the most elegant way but somehow I think it gives what you want. 我相信这不是最优雅的方式,但不知怎的,我觉得它给你想要的东西。 You can use a for-loop 您可以使用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
  }
}

OUTPUT OUTPUT

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM