[R] Return the matrix location of multiple entries

David Winsemius dwinsemius at comcast.net
Mon Jan 23 20:40:39 CET 2012


On Jan 23, 2012, at 2:30 PM, Petr Savicky wrote:

> On Mon, Jan 23, 2012 at 01:08:03PM -0500, R. Michael Weylandt wrote:
>> I'd do something like
>>
>> apply(subER, 1, function(x) which(x %in% sort(x)[1:4]))
>>
>> E.g.
>>
>> subER <- matrix(sample(100), 10)
>
> Hi.
>
> This is OK, if there are four smallest values, which
> are different from the rest. For the first row in
>
>  subER <- rbind(c(1, 2, 2, 3, 3, 3, 5, 6), 8:1)
>
> the function determines the bound 3 and returns the
> indices of the 6 positions with 1, 2, 3 from the first
> row. So, the result is not a matrix, but a list.
>
>  apply(subER, 1, function(x) which(x %in% sort(x)[1:4]))
>
>  [[1]]
>  [1] 1 2 3 4 5 6
>
>  [[2]]
>  [1] 5 6 7 8
>
> The following solves ties by choosing the smaller index.
>
>  apply(subER, 1, function(x) order(x)[1:4])
>
>       [,1] [,2]
>  [1,]    1    8
>  [2,]    2    7
>  [3,]    3    6
>  [4,]    4    5
>
> If the indices should be ordered, then try the following
>
>  apply(subER, 1, function(x) sort(order(x)[1:4]))
>
>       [,1] [,2]
>  [1,]    1    5
>  [2,]    2    6
>  [3,]    3    7
>  [4,]    4    8

And if only the lowest four instances were desired (in ascending  
order) then this would work (and I transposed to bring back to the  
original structure):

  t(apply(subER, 1, function(x) x[order(x)][1:4]))
      [,1] [,2] [,3] [,4]
[1,]    1    2    2    3
[2,]    1    2    3    4


-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list