Plastic Soul
Plastic Soul

Reputation: 494

find largest smaller element

I have two lists of indices:

 > k.start
 [1]    3   19   45  120  400  809 1001
 > k.event
 [1]   3   4  66 300

I need a list that contains, for each element of k.event, the largest value in k.start which is less than or equal to it. The desired result is

k.desired = c(3,3,45,120)

So, I'm trying to replicate this code, except without a for loop:

for (i in 1:length(k.start){
   k.start[max(which(k.event[i] > k.start))]
}

Thanks!

Upvotes: 1

Views: 81

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99351

You could use

vapply(k.event, function(x) max(k.start[k.start <= x]), 1)
# [1]   3   3  45 120

Upvotes: 2

Related Questions