[R] how to get values within a threshold

William Dunlap wdunlap at tibco.com
Fri Sep 13 16:44:18 CEST 2013


> findInterval(thresholds, values)
[1] 1 4 4 4 7

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Zhang Weiwu
> Sent: Friday, September 13, 2013 3:14 AM
> To: r-help at 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 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.



More information about the R-help mailing list