I am using cut
to divide my data into bins, which gives the resulting bin as something like (x1,x2]
. Can anyone tell me how I might make a new column that expresses these bins as the midpoint of the bin? For example, with the following dataframe:
structure(list(x = c(1L, 4L, 6L, 7L, 8L, 9L, 12L, 18L, 19L),
y = 1:9), .Names = c("x", "y"), class = "data.frame", row.names = c(NA,
-9L))
I can use
test$xRange <- cut(test$x, breaks=seq(0, 20, 5))
to give
x y xRange
1 1 1 (0,5]
2 4 2 (0,5]
3 6 3 (5,10]
4 7 4 (5,10]
5 8 5 (5,10]
6 9 6 (5,10]
7 12 7 (10,15]
8 18 8 (15,20]
9 19 9 (15,20]
But the result I need should instead look like:
x y xRange xMidpoint
1 1 1 (0,5] 2.5
2 4 2 (0,5] 2.5
3 6 3 (5,10] 7.5
4 7 4 (5,10] 7.5
5 8 5 (5,10] 7.5
6 9 6 (5,10] 7.5
7 12 7 (10,15] 12.5
8 18 8 (15,20] 17.5
9 19 9 (15,20] 17.5
I've done some searching, and came upon a similar question at divide a range of values in bins of equal length: cut vs cut2, which gives a solution as
cut2 <- function(x, breaks) {
r <- range(x)
b <- seq(r[1], r[2], length=2*breaks+1)
brk <- b[0:breaks*2+1]
mid <- b[1:breaks*2]
brk[1] <- brk[1]-0.01
k <- cut(x, breaks=brk, labels=FALSE)
mid[k]
}
But when I try this on my case, using
test$xMidpoint <- cut2(test$x, 5)
it does not return the correct midpoint. Perhaps I am entering the breaks incorrectly in cut2
? Can anyone tell me what I'm doing incorrectly?