Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return the index of a vector when the difference between the index and value satisfies a condition in r

Tags:

r

vector

I have been having trouble phrasing this question, so if anyone can edit it up to standard that would be great.

I have a vector that looks like this:

 x <- c(1, 2, 5)

How do i return the last index where the difference between the value of the vector in that position and the position is = 0.

In this case, I would like to have

 2

as the difference between the value of the vector and its position for the third element is > 0

 x[3]-3.

As a side note, this is part of a larger function, where the vector 'x' was built as a vector of values that satisfy a condition (being outside of a range). In this example, the vector 'x' was built as the indexes of the vector

 y <- c(1, -0.544099347708607, 0.0330854828196116, 0.126862586350202, -0.189999318205021, 0.0709946572904202, -0.0290039765997793, 0.12201693346217, -0.120410983904152, 0.0974094609584081, -0.119147919464352, 0.0154264136176002, 0.115102403861495, -0.145980255860186, 0.116998886386955, -0.137041816761002, 0.114352714471954, 0.0228895094121642, -0.0679735427311049, 0.0350071153004831, -0.0145366468920295)

Which are outside of the range (-.18, .18)

 plot.ts(y)
 abline(h = 0.18)
 abline(h = -0.18)
like image 746
erasmortg Avatar asked Dec 05 '25 04:12

erasmortg


1 Answers

You can use the Position function:

Position(function(x) {x == 0}, x - 1:length(x), right=T)

See http://stat.ethz.ch/R-manual/R-devel/library/base/html/funprog.html for more functions.

Or as @Frank said below,

Position(`!`, x - 1:length(x), right=T)

This is because 0 is falsey and other numbers are truthy.

like image 60
zw324 Avatar answered Dec 07 '25 20:12

zw324



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!