Find values that are between list of numbers

非 Y 不嫁゛ 提交于 2021-02-17 05:39:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!