Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return last non-zero element index in r

Tags:

r

If

a <- c(6,4,5,6,2,6,0,0,1,3,7,0,0) # index is 11

I need the column index of 7.

Purpose:

I need to reassign value to the last non-zero element, which is the 7 in the above case.

It's guaranteed that the vector a always ends with N consecutive zeros, where N unknown.

like image 533
Lovnlust Avatar asked Mar 16 '23 00:03

Lovnlust


1 Answers

You can try

 tail(which(a!=0),1)
 #[1] 11
like image 185
akrun Avatar answered Mar 18 '23 15:03

akrun