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)

      

+3


source to share


4 answers


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.

+4


source


Here's another approach:

index <- 1:length(x)
max(which(x - index == 0))
#[1] 2

      



Or, as another Frank points out, you can check for equality instead of 0 difference.

max(which(x == index))

      

+3


source


I think the simplest approach is to check for equality rather than checking that the difference is zero:

tail(which(x==seq_along(x)),1)
# 2

      

+3


source


You can also try this

tail(which((1:length(x)-x)==0),1)

      

0


source







All Articles