R-Conditional calculation based on a reference to the values ​​in another line

I would like to reference the value in the same column on another row. I have one column with start and stop. I would like to add a column that indicates whether the machine is working or not.

Here's what the data looks like:

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

The result 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:

  • In the event that the first column of the first row is equal to the beginning → works
  • ELSE IF the previous column of the first row is stop → ""
  • ELSE same value as previous row for second column

How can I do this in an elegant way using R?

Thanks so much for your input!

+4
source share
2

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

, , - , , . 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

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

Source: https://habr.com/ru/post/1623277/


All Articles