Based on @David H"s answer, with 2 options to choose from:
- Generate intervals with
cut()
using a vector of breaks
- Generate intervals with
floor()
instead of cut()
Create data
set.seed(33)
d <- data.frame(v1=seq(0,9.9,0.1),
v2=rnorm(100),
v3=rnorm(100))
Generate intervals with cut()
using a vector of breaks
For that simple example you could use breaks <- 0:10
but to be more general let's take the min and max of d$v1
.
breaks <- floor(min(d$v1)):ceiling(max(d$v1))
breaks
# [1] 0 1 2 3 4 5 6 7 8 9 10
Summarise over intervals 0-0.99, 1-1.99, 2-2.99, 3-3.99,....
d %>%
mutate(interval = cut(v1,
breaks,
include.lowest = TRUE,
right = FALSE)) %>%
group_by(interval) %>%
summarise( mean.v2 = mean(v2) , mean.v3 = mean(v3))
# Source: local data frame [10 x 3]
#
# interval mean.v2 mean.v3
# (fctr) (dbl) (dbl)
# 1 [0,1) -0.13040624 -0.20781247
# 2 [1,2) 0.26505794 0.51990167
# 3 [2,3) 0.13451628 1.12066174
# 4 [3,4) 0.23451272 -0.14773437
# 5 [4,5) 0.34326922 0.28567969
# 6 [5,6) -0.77059944 -0.16629580
# 7 [6,7) -0.17617190 0.03320797
# 8 [7,8) 0.86550135 -0.24664350
# 9 [8,9) -0.06652047 -0.27798769
# 10 [9,10] -0.10424865 0.24060163
Generate intervals with floor()
instead of cut()
Cheat a little bit by subtracting a tiny number 1e-9
from the end of each interval.
d %>%
mutate(start = floor(v1), end = start + 1 - 1e-9 ) %>%
group_by(start, end) %>%
summarise_each(funs(mean))
# Source: local data frame [10 x 4]
# Groups: start [?]
#
# start end mean.v2 mean.v3
# (dbl) (dbl) (dbl) (dbl)
# 1 0 1 -0.13040624 -0.20781247
# 2 1 2 0.26505794 0.51990167
# 3 2 3 0.13451628 1.12066174
# 4 3 4 0.23451272 -0.14773437
# 5 4 5 0.34326922 0.28567969
# 6 5 6 -0.77059944 -0.16629580
# 7 6 7 -0.17617190 0.03320797
# 8 7 8 0.86550135 -0.24664350
# 9 8 9 -0.06652047 -0.27798769
# 10 9 10 -0.10424865 0.24060163