Remove zeros in the start and end of a vector

前端 未结 4 609
鱼传尺愫
鱼传尺愫 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: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
    

提交回复
热议问题