Re: Selecting Rows Based on Column Values
- To: mathgroup at smc.vnet.net
- Subject: [mg101557] Re: Selecting Rows Based on Column Values
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Fri, 10 Jul 2009 06:43:52 -0400 (EDT)
On 7/8/09 at 7:10 AM, wu.x.cynthia at gmail.com (cynthia wu) wrote:
>I've been trying to use the Select Command to select only the rows
>that have the a specific value in a specific column. I have, for
>example, the following matrix (4x3):
>tester={{1, 3, 1}, {3, 1, 0}, {4, 2, 1}, {5, 6, 2}}
>I want to select the rows that have values ==1 in the 3rd column.
>I've tried:
>select(tester, #[[All,3]]==1&), but I get an error saying that my
>request violates the matrix boundaries.
>The desired output should be: {{1,3,1}, {4,2,1}}.
You are close. What the selector operates on is an individual
row of your matrix. So instead of
#[[All,3]]==1&
all you need is
#[[3]]==1&
Any of the following do what you want
In[2]:= Select[tester, #[[3]] == 1 &]
Out[2]= {{1, 3, 1}, {4, 2, 1}}
In[3]:= Select[tester, Last[#] == 1 &]
Out[3]= {{1, 3, 1}, {4, 2, 1}}
In[4]:= Cases[tester, {__, 1}]
Out[4]= {{1, 3, 1}, {4, 2, 1}}