在 R 中的数据框中创建条件序列

Create conditional sequence in dataframe in R

希望用条件序列填充矩阵。数据中有多个中断,但必须维护这些 breaks/spaces。

这是我要完成的示例矩阵。第一列是原始数据。第二列是我要创建的。

try <- matrix(c(rep(0,4),rep(1,3),rep(0,2),rep(1,2), rep(0,4), seq(1,3,1), rep(0,2), seq(4,5,1)),ncol=2)

我试过使用 seq_long、while 循环等,但似乎无法正常工作。任何 help/pointers 将不胜感激。

try 视为您的数据(第 1 列),您可以:

try$second_column <- cumsum(try[,1])*try[,1]

也许以下两步解决方案就是您想要的。

try[, 2] <- ave(try[, 1], try[, 1], FUN = seq_along)
try[try[, 1] == 0, 2] <- 0

try[, 2]
#[1] 0 0 0 0 1 2 3 0 0 4 5

一行是

ave(try[, 1], try[, 1], FUN = function(x) if(any(x == 0)) x else seq_along(x))
#[1] 0 0 0 0 1 2 3 0 0 4 5