Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first greater element with higher index

Tags:

r

I have two vectors, A and B. For every element in A I want to find the index of the first element in B that is greater and has higher index. The length of A and B are the same.

So for vectors:

A <- c(10, 5, 3, 4, 7)

B <- c(4, 8, 11, 1, 5)

I want a result vector:

R <- c(3, 3, 5, 5, NA)

Of course I can do it with two loops, but it's very slow, and I don't know how to use apply() in this situation, when the indices matter. My data set has vectors of length 20000, so the speed is really important in this case.

A few bonus questions:

  1. What if I have a sequence of numbers (like seq = 2:10), and I want to find the first number in B that is higher than a+s for every a of A and every s of seq.

  2. Like with question 1), but I want to know the first greater, and the first lower value, and create a matrix, which stores which one was first. So for example I have a of A, and 10 from seq. I want to find the first value of B, which is higher than a+10, or lower than a-10, and then store it's index and value.

like image 850
mikabast Avatar asked Dec 01 '12 09:12

mikabast


1 Answers

sapply(sapply(seq_along(a),function(x) which(b[-seq(x)]>a[x])+x),"[",1)
[1]  3  3  5  5 NA
like image 72
James Avatar answered Sep 21 '22 10:09

James