Hi Bill, Great soluiton! Just to add: if values are not sorted (in this case, okay)
set.seed(434) val1<- rnorm(1e5) set.seed(28) thresh1<- sample(1:20,1e2,replace=TRUE) system.time(res11<- findInterval(thresh1,val1)) #Error in findInterval(thresh1, val1) : # 'vec' must be sorted non-decreasingly system.time(res<- findInterval(thresh1,sort(val1))) # user system elapsed # 0.012 0.000 0.014 system.time(res2<- sapply(thresh1,function(x) {sum(val1<x)})) # user system elapsed # 0.088 0.000 0.087 identical(res2,res) #[1] TRUE A.K. ----- Original Message ----- From: William Dunlap <wdun...@tibco.com> To: Zhang Weiwu <zhangwe...@realss.com>; "r-help@r-project.org" <r-help@r-project.org> Cc: Sent: Friday, September 13, 2013 10:44 AM Subject: Re: [R] how to get values within a threshold > findInterval(thresholds, values) [1] 1 4 4 4 7 Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com > -----Original Message----- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On > Behalf > Of Zhang Weiwu > Sent: Friday, September 13, 2013 3:14 AM > To: r-help@r-project.org > Subject: [R] how to get values within a threshold > > > input: > > > values > [1] 0.854400 1.648465 1.829830 1.874704 7.670915 7.673585 7.722619 > > > thresholds > [1] 1 3 5 7 9 > > expected output: > > [1] 1 4 4 4 7 > > That is, need a vector of indexes of the maximum value below the threshold. > > e.g. > First element is "1", because value[1] is the largest below threshold "1". > Second element is "4", because value[4] is the largest below threshold "3". > > The way I do it is: > > > sapply(1:length(threshold), function(x) { length(values[values < > > threshold[x]])}) > [1] 1 4 4 4 7 > > It just seem to me too long and stupid to be like R. Is it already the best > way? > > Somehow I feel which() was designed for a purpose like this, but I couldn't > figure out a way to apply which here. > > ______________________________________________ > R-help@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. ______________________________________________ R-help@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. ______________________________________________ R-help@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.