将数字映射到R中的数字向量中的最小值



给定一个数字向量,我想将每个数字映射到数字不超过的单独向量中的最小值。例如:

# Given these
v1 <- 1:10
v2 <- c(2, 5, 11)
# I'd like to return
result <- c(2, 2, 5, 5, 5, 11, 11, 11, 11, 11)

Try

cut(v1, c(0, v2), labels = v2)
 [1] 2  2  5  5  5  11 11 11 11 11
Levels: 2 5 11

,可以使用as.numeric(as.character(...))转换为数字向量。

另一种方式(感谢编辑@Ananda)

v2[findInterval(v1, v2 + 1) + 1]
#  [1]  2  2  5  5  5 11 11 11 11 11]

相关内容

最新更新