Hao Cen
2009-Dec-02 14:34 UTC
[R] find the index of the next largest element in a sorted vector
Hi, How can I find the index of the next largest element in a sorted vector if an element is not found. for example, searching 2 in c(0,3,4) would return 1 since 2 is not in the vector and 0 is the next largest element to 2. I tried which and match and neither returns such information.> which(c(0,3,4) == 2)integer(0)> match(2, c(0,3,4))[1] NA thanks Jeff
David Winsemius
2009-Dec-02 15:14 UTC
[R] find the index of the next largest element in a sorted vector
On Dec 2, 2009, at 9:34 AM, Hao Cen wrote:> Hi, > > How can I find the index of the next largest element in a sorted > vector if > an element is not found. > > for example, searching 2 in c(0,3,4) would return 1 since 2 is not > in the > vector and 0 is the next largest element to 2. > > I tried which and match and neither returns such information. > >> which(c(0,3,4) == 2) > integer(0) >> match(2, c(0,3,4)) > [1] NATake a look at these. I changed to problem so that the "answer would be in the middle of the sequence. > which(c(0,3,4) <= 2) [1] 1 # but which would have retruned several values if the match were in the middle > which(c(-3,-1, 0,3,4) <= 2) [1] 1 2 3 > tail(which(c(-3,-1,0,3,4) <= 2),1) [1] 3 # the desired index -- David Winsemius, MD Heritage Laboratories West Hartford, CT
jim holtman
2009-Dec-02 15:26 UTC
[R] find the index of the next largest element in a sorted vector
Is this what you want:> x <- c(0,3,4) > ?findInterval > findInterval(2, x)[1] 1>On Wed, Dec 2, 2009 at 9:34 AM, Hao Cen <hcen at andrew.cmu.edu> wrote:> Hi, > > How can I find the index of the next largest element in a sorted vector if > an element is not found. > > for example, searching 2 in c(0,3,4) would return 1 since 2 is not in the > vector and 0 is the next largest element to 2. > > I tried which and match and neither returns such information. > >> which(c(0,3,4) == 2) > integer(0) >> match(2, c(0,3,4)) > [1] NA > > > thanks > > Jeff > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >-- Jim Holtman Cincinnati, OH +1 513 646 9390 What is the problem that you are trying to solve?