[R] Selecting subset of a given vector

David Winsemius dwinsemius at comcast.net
Fri Jul 8 21:42:40 CEST 2011


On Jul 8, 2011, at 3:16 PM, Nipesh Bajaj 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.

An odd number of values would be easier to "center" around the closest  
to zero value. Here is a reduced example that picks out the 7 values  
(3 on either side of the closest to zero whose order statistic is  
closest to the value closest to zero:

 > x <- rnorm(20) # Sorry, forgot to set.seed()
 > ?which min
 > sort(x)[which.min(abs(sort(x))]
# closest to zero is the 9th value in sort(x)
 > sort(x)[(which.min(abs(sort(x)))-3):(which.min(abs(sort(x)))+3)]
[1] -0.15579551 -0.05612874 -0.04493361 -0.01619026  0.07456498   
0.38984324
[7]  0.41794156

-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list