R filter rows based on an element

I need to separate a matrix based on the existence of an element in a row.  I will end up with two matrices: the first will not contain the element on any of its rows and the second will contain the element in all its rows.

I first use apply to get the row indices, and then I create new matrices based on those indices.  Here are the commands:

oi = apply(tr, 1, function(row) any(1 %in% row));
1 = matrix ( data=c(tr[,1:2][oi]), ncol=2 );
2 = matrix ( data=c(tr[,1:2][!oi]), ncol=2 );

Note that the “tr” in the first line is my original matrix.  And “oi” is the is  logical vector containing TRUE if element (in this case 1) is in the row and FALSE otherwise.  Since I only want the first two columns of the matrix I use [,1:2] as my index.

Advertisement

About joelgranados

I'm fascinated with how technology and science impact our reality and am drawn to leverage them in order to increase the potential of human activity.
This entry was posted in PhD, R. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s