考慮以下data.frame
,子data.frame工會多個間隔
d <- data.frame(x = seq(0, 10, length=100), value = rnorm(100))
我想子集基於x
屬於任何以下區間,
intervals <- list(c(0.2, 0.8), c(1, 2), c(8, 8.2))
test <- function(range, x){
which(x >= range[1] & x <= range[2])
}
d[Reduce(`union`, lapply(intervals, test, x=d$x)), ]
現在,測試功能似乎多餘的,因爲它看起來非常像內置的findInterval
,但我找不到一個優雅的方式來使用它。
condition <- Reduce(`|`, lapply(lapply(intervals, findInterval,
x=d$x, all.inside=FALSE), `==`, 1))
d[condition, ]
你能提出更好的建議嗎?
謝謝,但'切'感覺像一個矯枉過正的,不是嗎? – baptiste 2012-02-08 22:53:32
@baptiste OK,增加了一個'findInterval'解決方案 – James 2012-02-08 23:48:08
很好,它也消除了'Reduce'中'for'循環的需要 – baptiste 2012-02-09 00:03:55