R 查找与一系列值匹配的行
我正在尝试获取范围内数字的列R 查找与一系列值匹配的行,r,R,我正在尝试获取范围内数字的列importantval。我甚至不知道怎么开始,有人有什么想法吗 data<-data.frame(lower=c(1,4,6,7,7),upper=c(3,5,7,8,9),importantval=c(99,98,97,96,95)) vals<-c(1.14,3.5,7.2,19) > data lower upper importantval 1 1 3 99 2 4 5
importantval
。我甚至不知道怎么开始,有人有什么想法吗
data<-data.frame(lower=c(1,4,6,7,7),upper=c(3,5,7,8,9),importantval=c(99,98,97,96,95))
vals<-c(1.14,3.5,7.2,19)
> data
lower upper importantval
1 1 3 99
2 4 5 98
3 6 7 97
4 7 8 96
5 7 9 95
data一个简单的lappy
就可以了。识别线路相对容易。当多个值起作用时,if语句只取较小的间隔有点难理解,但大多数情况下,如果存在多个可能性,我取间隔等于可能的最小间隔的行
foo <- function(i) {
res <- data[data$lower < i & data$upper > i, ]
if (nrow(res) > 1) {
res <- res[which(res$upper - res$lower == min(res$upper - res$lower)), ]
}
if (nrow(res) == 0) return(NA)
return(res$importantval)
}
results <- data.frame(vals, sapply(vals, foo))
为什么在4到5之间没有VAL
的情况下98是匹配的?不匹配,这在我的示例中是一个输入错误…修复了,谢谢!
foo <- function(i) {
res <- data[data$lower < i & data$upper > i, ]
if (nrow(res) > 1) {
res <- res[which(res$upper - res$lower == min(res$upper - res$lower)), ]
}
if (nrow(res) == 0) return(NA)
return(res$importantval)
}
results <- data.frame(vals, sapply(vals, foo))
results <- lapply(vals, foo)
names(results) <- vals