简体   繁体   中英

How to select rows in a dataframe based on values in a column

I have dataframe "fish" which has 3 columns. The dataframe is sorted by values in column 1. I want to select the rows based on the lowest values in column 3. How do I select only these rows?? I am trying to graph the data in column 1 by the lowest column 3 values.

This code creates a dataframe and returns the rows with the three lowest values for the column we've called unif . You'll already have the dataframe, so you just need to select the column you want to filter based on. Where I've used unif , you'd use whatever your column's name is.

## create the dataframe
n = 10 
df = data.frame(round(runif(n),1), round(rnorm(n),1))
colnames(df) = c('unif', 'norm')
   unif norm
1   0.4  0.7
2   0.4  0.2
3   0.3  1.3
4   0.8 -0.4
5   0.3 -0.6
6   0.3  1.8
7   0.5 -1.0
8   0.4  0.4
9   0.0  0.2
10  0.6 -0.6

With that dataframe, we just need to filter the rows to the rows with the lowest three values on the unif column.

## return the rows with the three lowest values 
df[order(df$unif)[(1:3],]   #### This is the part you need

Will return this result, which is I think what you want:

   unif norm
7   0.5 -1.0
10  0.6 -0.6
4   0.8 -0.4

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