[R] Selecting subset of a given vector

Dennis Murphy djmuser at gmail.com
Fri Jul 8 21:48:54 CEST 2011


Hi:

Do you want the N points in the vector closest to a fixed point? If
so, then try this:

f <- function(vec, center, nselect) {
    d <- (vec - center)^2
    vec[order(d)][1:nselect]
  }

v <- rnorm(1000)
f(v, 0, 10)    # select the ten points in v closest to zero

Your goal is subject to multiple interpretations, so if this is not
what you require, perhaps you should sharpen your question.

HTH,
Dennis

On Fri, Jul 8, 2011 at 12:16 PM, Nipesh Bajaj <bajaj141003 at gmail.com> wrote:
> Hi there, given a numeric vector, I can select numbers within a
> specific range. However presently, I have something related but
> different problem. Suppose I have a numeric vector. Now take an
> arbitrary number. Goal to to chose a specific subset with a given
> length, from that given vector, so that those chosen numbers are
> centered around that given constant.
>
> Here is one example:
>
> ### My original vector
> Vec <- rnorm(1000)
>
> ### Now chose some arbitrary number
> Number <- 0
>
> ### Chose the length of the resulting vector
> New.Len <- 10
>
> Now I have to chose 10 numbers from 'Vec' around 'Number'. If my 'Vec'
> contains one or more zero then those zero(s) also be selected.
>
>
> Can somebody help me with some pointer how can I achieve that?
>
> Thanks,
>
> ______________________________________________
> 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