Remove zeros in the start and end of a vector

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

提交回复
热议问题