简体   繁体   中英

Extracting a row from a data frame in R

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.

Another way is to use which.min

A[which.min(A[, 3]), ]
##[1] 2 4 3

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM