Remove zeros in the start and end of a vector

前端 未结 4 619
鱼传尺愫
鱼传尺愫 2021-01-12 13:58

I have a vector like this:

x <-  c(0, 0, 0, 0, 4, 5, 0, 0, 3, 2, 7, 0, 0, 0)

I want to keep only the elements from position 5 to 11. I w

相关标签:
4条回答
  • 2021-01-12 14:07

    Try this:

    x[ min( which ( x != 0 )) : max( which( x != 0 )) ]
    

    Find index for all values that are not zero, and take the first -min and last - max to subset x.

    0 讨论(0)
  • 2021-01-12 14:11

    This would also work :

    x[cumsum(x) & rev(cumsum(rev(x)))]
    # [1] 4 5 0 0 3 2 7
    
    0 讨论(0)
  • 2021-01-12 14:18

    You can try something like:

    x=c(0,0,0,0,4,5,0,0,3,2,7,0,0,0)
    rl <- rle(x)
    
    if(rl$values[1] == 0)
        x <- tail(x, -rl$lengths[1])
    if(tail(rl$values,1) == 0)
        x <- head(x, -tail(rl$lengths,1))
    
    x
    ## 4 5 0 0 3 2 7
    

    Hope it helps,

    alex

    0 讨论(0)
  • 2021-01-12 14:29

    I would probably define two functions, and compose them:

    trim_leading <- function(x, value=0) {
      w <- which.max(cummax(x != value))
      x[seq.int(w, length(x))]
    }
    
    trim_trailing <- function(x, value=0) {
      w <- which.max(cumsum(x != value))
      x[seq.int(w)]
    }
    

    And then pipe your data through:

    x %>% trim_leading %>% trim_trailing
    
    0 讨论(0)
提交回复
热议问题