Returns the index of the vector when the difference between index and value satisfies the condition in r
I'm having trouble phrasing this question, so if someone can edit it to standard it would be great.
I have a vector that looks like this:
x <- c(1, 2, 5)
How to return the last index where the difference between the vector value at that position and the position is = 0.
In this case, I would like to have
2
since the difference between the value of the vector and its position for the third element is a> 0
x[3]-3.
As a side note, this is part of a larger function where the vector "x" was constructed as a vector of values that satisfy the condition (out of range). In this example, the vector "x" was built as the indices 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 out of range (-18, 18)
plot.ts(y) abline(h = 0.18) abline(h = -0.18)
source to share
You can use the function Position
:
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 details .
Or like @Frank below,
Position(`!`, x - 1:length(x), right=T)
This is due to the fact that it 0
is false and other numbers are true.
source to share