我想在另一行的同一列中引用一个值。我有一栏有开始和停止时刻。我想添加一个列,指示机器是否正在运行。
这就是数据的样子:
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,] "" ""
在第二栏中我想做:
如何以优雅的方式使用R?
非常感谢您提前输入!
答案 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" ""