[R] Find pattern in matrix
David Winsemius
dwinsemius at comcast.net
Tue Jul 26 01:42:18 CEST 2011
On Jul 21, 2011, at 6:12 PM, Q wrote:
> Hello all,
>
> I'm trying to find all combinations of 4 numbers that satisfy 4
> criteria,
> inside of a matrix (62 x 25). I've found a way to do this using for
> loops,
> but it is extremely slow because it involves checking every possible
> combination of numbers (567300) to see if the criteria are
> satisfied. Do
> you think there is a faster method of doing this? Or some functions
> that
> might help me out?
>
> The matrix is of species abundances, with each row representing a
> species
> (A,B,C...) and each column representing a site (1,2,3...). The
> numbers in
> the matrix tell the abundance of the species at that site:
>
>
>
>> 1 2 3...
>> A 0 5 6...
>> B 7 8 2...
>> C 4 1 3...
>> ...
>>
>
> I'm trying to find combinations of species/sites such that
> A1>B1,A1>A2,B2>B1,B2>A2
>
> I have used expand.grid to get all combinations of species pairs and
> site
> pairs, and then checked to see if the inequalities are satisfied.
> However,
> as I said, it takes forever.
>
> I tried to write a function that would take vectors and trick R into
> searching for my pattern:
>
>
>
>> count <- function(i,j,k,l){
>> length(matrix[matrix[i,k] > matrix[i,l] &&
>> matrix[i,k] > matrix[j,k] &&
>> matrix[j,l] > matrix[j,k] &&
>> matrix[j,l] > matrix[i,l]])
>> }
>>
>
> That didn't work. So I wonder if anyone has any ideas of another
> way to
> proceed or functions I could look up that would head me in the right
> direction.
My idea:
Build a small test set that contains sufficient complexity to
represent you problem and work with that. Then, when you get ready to
post another letter to rhelp you will be able to present the problem
explicitly by using dput() on your objects and show what kind of
errors are preventing execution.
(I am giving up on creating examples for people unless it is trivial.)
My own experience is that usually when I take that step with problems
I am considering asking for assistance, the problem "solves itself" in
the process of constructing the posting. I would be embarrassed to
post an example that looked like;
>> 1 2 3...
>> A 0 5 6...
>> B 7 8 2...
>> C 4 1 3...
>> ...
That's not an example. It may be a puzzle of sorts, but it is _not_ a
reproducible example.
> Something fully fleshed out isn't necessary.
But something reproducible is ... (or should be.)
--
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list