[R] how to get the position of a vector-value

Katharine Mullen kate at few.vu.nl
Wed Jul 30 02:44:37 CEST 2008


One way:

x <- abs(1.5 - c(1.0,1.2,1.4,1.6,1.8,2.0))
which(x==min(x))

On Wed, 30 Jul 2008, [ISO-8859-1] Jörg Groß wrote:

> I am searching for a way to get nearest position of a number in a
> vector from a search-value.
>
> So perhaps if I have this vector:
> 1.0   1.2   1.4   1.6   1.8   2.0
>
> I want to get the position of a special number.
>
> with match(1.4 ,x), I get "3" for position three.
>
> But now I want the nearest number in that vector from perhaps 1.5 (the
> mean).
>
>
>
> I tried it with sequences:
>   match(seq(from=1.1, to=1.6, by=.1),x)
>
> but what I get is:
> [1] NA NA NA NA NA  4
> (instead of (NA 2 NA 3 NA 4).
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list