I would like to find the group in vector according the close value, like this:
x <- c(1.001, 1.002, 1.003, 2.0)
and then calculate the mean of group [c(1.001, 1.002, 1.003)] which diff value < 0.1
result <- c(1.002,1.002,1.002,2)
Thanks!
hees
>Solution :
Here is a solution that also handles unordered vectors:
x <- c(1.001, 1.002, 2.0, 1.003, 2.01, 3)
o <- order(x)
y <- x[o]
g <- cumsum(c(0, diff(y)) >= 0.1)
res <- tapply(y, g, mean)[as.character(g)]
res[o]
# 0 0 1 0 1 2
#1.002 1.002 2.005 1.002 2.005 3.000