Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select the close value in vector in R?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading