Message Boards Message Boards

0
|
2874 Views
|
3 Replies
|
3 Total Likes
View groups...
Share
Share this post:

[?] Extract data from a table with four columns?

I have a table with 4 columns. In the fourth column there is either a 0 or 1. I would like to know how to delete rows in the table that have a 0 in the fourth column? I've tried converting the table to a dataset but can figure out how to use Select for the fourth column because it has no name.

Or conversely, I would like to make a new table with the row data that has a 1 in the fourth colum

POSTED BY: Fred Diether
3 Replies
Posted 5 years ago

Examples using Select and Cases:

In[1]:= m = Table[RandomInteger[], 10, 4]
Out[1]= {{0, 0, 1, 0}, {1, 0, 0, 1}, {0, 1, 1, 1}, {0, 0, 0, 1}, {0, 
  1, 0, 1}, {0, 0, 1, 0}, {0, 0, 1, 1}, {1, 0, 1, 1}, {1, 1, 1, 0}, {1, 0, 0, 0}}

In[2]:= Select[m, Last[#] == 1 &]
Out[2]= {{1, 0, 0, 1}, {0, 1, 1, 1}, {0, 0, 0, 1}, {0, 1, 0, 1}, {0, 0, 1, 1}, {1, 0, 1, 1}}

In[3]:= Cases[m, {_, _, _, 1}]
Out[3]= {{1, 0, 0, 1}, {0, 1, 1, 1}, {0, 0, 0, 1}, {0, 1, 0, 1}, {0, 0, 1, 1}, {1, 0, 1, 1}}

This form will also work:

Cases[m, {__, 1}]
POSTED BY: Hans Milton

Hi Hans,

Many thanks. The first example with Select works perfectly. I didn't know to put the ampersand at the end. Why is that necessary?

POSTED BY: Fred Diether
Posted 5 years ago

The & denotes that what's before is the body of a pure function. One can also say that it is a shorthand for Function. These forms are equivalent:

Select[m, Last[#] == 1 &]

Select[m, Function[Last[#] == 1]]

Check out this and this

POSTED BY: Hans Milton
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract