erasmortg
erasmortg

Reputation: 3278

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

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)

Upvotes: 3

Views: 136

Answers (4)

Akash
Akash

Reputation: 201

One can also try this

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

Upvotes: 0

Jota
Jota

Reputation: 17611

Here is another approach:

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

Or as the other Frank points out, you could test for equality instead of the difference being 0.

max(which(x == index))

Upvotes: 3

zw324
zw324

Reputation: 27180

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.

Upvotes: 4

Frank
Frank

Reputation: 66819

I think the simplest approach is to test equality, not test for the difference being zero:

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

Upvotes: 3

Related Questions