Skip to content
Prev 32136 / 398506 Next

Efficient subsetting

Here I have a general solution. x need not be ordered and ranges need not 
be equally spaced.

x <- c(1,1,2,3,4,5)
y <- c(2,3,3,4,5,6)
xcut <- cut(x,breaks=c(1,3,5),right=F)

#If you want the FIRST value of y whose x are in the range
wh <- !duplicated(xcut) & !is.na(xcut)
y[wh]         #   [1] 2 4

#If you want the LAST value of y whose x are in the range
revxcut <- rev(xcut)
wh <- rev(!duplicated(revxcut) & !is.na(revxcut))
y[wh]         #   [1] 3 5

HTH,
Jerome
On May 16, 2003 11:16 am, R A F wrote: