[R] how to get values within a threshold

Zhang Weiwu zhangweiwu at realss.com
Fri Sep 13 12:13:45 CEST 2013


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.



More information about the R-help mailing list