Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove zeros in the start and end of a vector

Tags:

r

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 want to delete the zeroes in the start and end. For this vector it is quite easy since it is small.

I have very large data and need something in general for all vectors.

like image 252
Sayak Avatar asked Jun 03 '14 08:06

Sayak


1 Answers

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.

like image 90
zx8754 Avatar answered Sep 17 '22 09:09

zx8754