0

Let's say we have a matrix something like this:

> A = matrix( 
+   c(2, 4, 3, 1, 5, 7), # the data elements 
+   nrow=2,              # number of rows 
+   ncol=3,              # number of columns 
+   byrow = TRUE)        # fill matrix by rows 

> A                      # print the matrix 
     [,1] [,2] [,3] 
[1,]    2    4    3 
[2,]    1    5    7

Now, I just used this small example, but imagine if the matrix was much bigger, like 200 rows and 5 columns etc. What I want to do, is to get the minimum value from column 3, and extract that row. In other words, find and get the row where is the 3rd attribute the lowest in the entire column of that data frame.

dataToReturn <- which(A== min(A[, 3])

but this doesn't work.

2
  • In case of multiple rows meeting the minimum condition, do you want to return only the first row that meets the minimum or all rows that have the minimum value in column 3? Commented Jun 1, 2014 at 14:48
  • all rows that meet the condition should be returned Commented Jun 1, 2014 at 14:51

2 Answers 2

2

Another way is to use which.min

A[which.min(A[, 3]), ]
##[1] 2 4 3
Sign up to request clarification or add additional context in comments.

3 Comments

This is correct. But there is of course a difference if you have multiple rows with a minimum. In such a case, which.min will only return the first row, whereas in my answer, all rows meeting the criteria, would be returned. So it really depends on the intention.
Yes, I need all rows that meet the criteria, then which.min is not a viable solution ?
No, in that case, which.min is not the right solution for you. From the ?which.min help page: "Determines the location, i.e., index of the (first) minimum or maximum of a numeric (or logical) vector."
1

You can do this with a simple subsetting via [] and min:

A[A[,3] == min(A[,3]),]
[1] 2 4 3

This reads: Return those row(s) of A where the value of column 3 equals the minimum of column 3 of A.

If you have a matrix like this:

A <- matrix(c(2,4,3,1,5,7,1,3,3), nrow=3, byrow = T)
> A
     [,1] [,2] [,3]
[1,]    2    4    3
[2,]    1    5    7
[3,]    1    3    3

> A[which.min(A[, 3]), ]      #returns only the first row with minimum condition
[1] 2 4 3

> A[A[,3] == min(A[,3]),]     #returns all rows with minimum condition
     [,1] [,2] [,3]
[1,]    2    4    3
[2,]    1    3    3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.