Remove zeros in the start and end of a vector

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

提交回复
热议问题