In R with a matrix:
one two three four
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 11 18
[4,] 4 9 11 19
[5,] 5 10 15 20
I want to extract the submatrix whose rows have column three = 11. That is:
one two three four
[1,] 1 6 11 16
[3,] 3 8 11 18
[4,] 4 9 11 19
I want to do this without looping. I am new to R so this is probably very obvious but the documentation is often somewhat terse.
I will choose a simple approach using the dplyr package.
If the dataframe is data.
This is easier to do if you convert your matrix to a data frame using as.data.frame(). In that case the previous answers (using subset or m$three) will work, otherwise they will not.
To perform the operation on a matrix, you can define a column by name:
Or by number:
Note that if only one row matches, the result is an integer vector, not a matrix.
The following command will select the first row of the matrix above.
And this will select the last three.
The result will be a matrix in both cases. If you want to use column names to select columns then you would be best off converting it to a dataframe with
Then you can select with
Or, you could use the subset command.
If your matrix is called
m
, just use :Subset is a very slow function , and I personally find it useless.
I assume you have a data.frame, array, matrix called
Mat
withA
,B
,C
as column names; then all you need to do is:In the case of one condition on one column, lets say column A
In the case of multiple conditions on different column, you can create a dummy variable. Suppose the conditions are
A = 10
,B = 5
, andC > 2
, then we have:By testing the speed advantage with
system.time
, thewhich
method is 10x faster than thesubset
method.