Search code examples
rmatrixseq

Create conditional sequence in dataframe in R


Looking to fill a matrix with a conditional sequence. There are multiple breaks in the data but these breaks/spaces must be maintained.

Here is a sample matrix for what I am trying to accomplish. The first column is the original data. The second column is what I am trying to create.

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)

I have tried using seq_long, while loop, etc. but cannot seem to get it working. Any help/pointers would be appreciated.


Solution

  • Maybe the following two steps solution is what you want.

    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
    

    A one-liner is

    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