问题
I have two list of numbers like below.
x <- c(1, 5, 10, 17, 21, 30)
y <- c(2, 7, 19)
In my dataset, x
divides 1 to 30 in different segments (from 1-5, 5-10, 10-17, 17-21, 21-30). Would it be possible to match these segments to numbers in y
? (In this case, I'd want to get c(1,5,17)
as an output because 2 is between 1 and 5, 7 is between 5 and 10, and 19 is in between 17 and 21.)
回答1:
You can do this with sapply
and a simple function
sapply(y, function(a) x[max(which(x<a))])
[1] 1 5 17
回答2:
?findInterval
to the rescue:
x[findInterval(y,x)]
#[1] 1 5 17
回答3:
Using cut
is another option
cut(y, breaks = x, labels = x[-length(x)])
#[1] 1 5 17
Could be also done with labels = FALSE
x[cut(y, breaks = x, labels = FALSE)]
#[1] 1 5 17
来源:https://stackoverflow.com/questions/52157512/find-values-that-are-between-list-of-numbers