[R] Return the matrix location of multiple entries

Petr Savicky savicky at cs.cas.cz
Mon Jan 23 20:30:02 CET 2012


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

Hope this helps.

Petr Savicky.



More information about the R-help mailing list