[R] Return the matrix location of multiple entries
Bert Gunter
gunter.berton at gene.com
Mon Jan 23 21:21:24 CET 2012
A couple of additional notes that may or may not be helpful...
1. Note that Michael's solution does exactly as requested and provided
the indices of the 4 smallest values. However it does not provide them
in the order of those values. A simpler construction that does is:
apply(subER, 1, function(x) order(x)[1:4] )
This also may be a tad faster.
2. For a (very) large number of columns and/or rows, partial sorting
could be somewhat faster, e.g via
apply(subER,1,function(x)which(sort.int(x,partial=1:4)[1:4] %in% x)))
3. Not mentioned, and perhaps irrelevant here -- but still... --, is
the question of what do you do if there are ties in the sorting? This
may be impossible in theory, but could happen in practice, e.g. due to
LOD issues for measurement.
Cheers,
Bert
On Mon, Jan 23, 2012 at 10:08 AM, R. Michael Weylandt
<michael.weylandt at gmail.com> 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)
>
> But I'll admit that seems clunkier than it should be.
>
> On Mon, Jan 23, 2012 at 12:41 PM, connollj <connollj at uoguelph.ca> wrote:
>> Hello!
>>
>> I'm working with a matrix called 'subER'. This matrix has 150(=h) rows and
>> 15 columns. What I would like to do is have a command that will identify the
>> minimum 4 values in each row and return the column numbers where these
>> values were found. My hope is to store this information in a new 150 by 4
>> matrix called P.
>>
>> So far I've only been able to get R to identify one minimum value and return
>> its corresponding column location:
>>
>> P=matrix(nrow=h, ncol=1)
>> for(i in 1:h){
>> P[i,]=which.min(subER[i,])
>> }
>>
>> Any help would be greatly appreciated!!
>>
>> Thank you in advance,
>>
>> Jess
>>
>>
>> --
>> View this message in context: http://r.789695.n4.nabble.com/Return-the-matrix-location-of-multiple-entries-tp4321412p4321412.html
>> Sent from the R help mailing list archive at Nabble.com.
>>
>> ______________________________________________
>> 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.
>
> ______________________________________________
> 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.
--
Bert Gunter
Genentech Nonclinical Biostatistics
Internal Contact Info:
Phone: 467-7374
Website:
http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm
More information about the R-help
mailing list