## 计算R中范围内的数值内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (36)

``````ra <- data.frame(a=c(0, 250, 500, 750), b=c(250, 500, 750, 900))
ra
a   b
1   0 250
2 250 500
3 500 750
4 750 900

ev <- data.frame(events=c(1,1,1,1,1), time=c(100, 200, 450, 550, 600))
ev
events time
1      1  100
2      1  200
3      1  500
4      1  550
5      1  600
``````

``````data.frame(a=c(0, 250, 500, 750), b=c(250, 500, 750, 900), hits=c(2,1,2,0))
a   b hits
1   0 250    2
2 250 500    1
3 500 750    2
4 750 900    0
``````

### 2 个回答

``````ra\$hits <- mapply(function(a, b) with(ev, sum(events[time > a & time < b])),
ra\$a,ra\$b)

ra
#     a   b hits
# 1   0 250    2
# 2 250 500    1
# 3 500 750    2
# 4 750 900    0
``````

``````library(tidyverse)
ra\$hits <-
pmap(ra, ~ ev %>% summarise(sum(events[between(time, .x, .y)]))) %>%
unlist
``````

``````library(sqldf)
ra\$hits <-
sqldf('
select    coalesce(sum(events), 0) as hits
from      ra
left join ev
on ev.time > ra.a and ev.time < ra.b
group by  ra.a
, ra.b
')[[1]]
``````

``````library(tidyverse)

crossing(ra, ev) %>%
group_by(a, b) %>%
summarise(hits = sum(between(time, a, b)))
``````

``````# A tibble: 4 x 3
# Groups:   a [4]
a     b  hits
<dbl> <dbl> <int>
1     0   250     2
2   250   500     1
3   500   750     2
4   750   900     0
``````