【发布时间】:2018-01-29 09:50:19
【问题描述】:
我有一组不重叠的间隔,每个间隔都有一个 ID。给定一个数字,我想根据它所属的间隔为其分配一个 ID(如果不存在这样的间隔,则为 NA)。
intervals_id <- structure(list(ID = c(851, 852, 999), Lower = c(85101, 85201,
85301), Upper = c(85104, 85206, 85699)), .Names = c("ID", "Lower",
"Upper"), row.names = c(NA, -3L), class = "data.frame")
# ID Lower Upper
# 1 851 85101 85104
# 2 852 85201 85206
# 3 999 85301 85699
value <- c(15555, 85102, 85201, 85206, 85207, 85600, 86999)
我使用cut 整理了一些东西,它似乎有效,但感觉很乱。任何想法更优雅和直接的解决方案?
intervals_id <- intervals_id[order(intervals_id$Lower),]
intervals_id$UpperP <- intervals_id$Upper + 0.01
position <- as.numeric(cut(value, breaks =
as.numeric(t(as.matrix(intervals_id[,c("Lower", "UpperP")]))), right = FALSE))
position[position %% 2 == 0] <- NA
position <- (position + 1) %/% 2
# desired result
data.frame(value, valueID = intervals_id$ID[position])
# value valueID
# 1 15555 NA
# 2 85102 851
# 3 85201 852
# 4 85206 852
# 5 85207 NA
# 6 85600 999
# 7 86999 NA
【问题讨论】:
标签: r