简体   繁体   English

计算R中范围内的数值

[英]Count number values in range in R

This is toy example. 这是玩具的例子。 I want to compare ra , which gives ranges (eg, time) and ev , which says when an event took place. 我想比较ra ,它给出范围(例如,时间)和ev ,它表示事件发生的时间。

I would like to make a new column hits in ra that says how many events took place in each range. 我想提出一个新的列hitsra ,上面写着许多事件是如何在每个范围内发生。

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

This is what the result should look like. 这就是结果应该是什么样子。

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

Could do: 能做:

library(tidyverse)

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

Output: 输出:

# 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

We can use a non-equi join in data.table 我们可以在data.table使用非equi连接

library(data.table)
setDT(ev)[ra, .(hits = .N), on = .(time > a, time < b), by = .EACHI]
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

Similar solution with tidyverse: 与tidyverse类似的解决方案:

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

Or, using similar logic to arg0naut and akrun's answers but in plain SQL (same result as above) 或者,使用与arg0naut和akrun的答案类似的逻辑但是在纯SQL中(与上面相同的结果)

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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM