Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset / filter rows in a data frame based on a condition in a column

Given a data frame "foo", how can I select only those rows from "foo" where e.g. foo$location = "there"?

foo = data.frame(location = c("here", "there", "here", "there", "where"), x = 1:5, y = 6:10) foo #   location x  y # 1     here 1  6 # 2    there 2  7 # 3     here 3  8 # 4    there 4  9 # 5    where 5 10 

Desired result, "bar":

#   location x y # 2    there 2 7 # 4    there 4 9 
like image 578
wishihadabettername Avatar asked Aug 10 '10 02:08

wishihadabettername


People also ask

How do you subset rows in R based on condition?

How to subset an R data frame with condition based on only one value from categorical column? First of all, create a data frame. Then, subset the data frame with condition using filter function of dplyr package.

How do you filter a DataFrame based on column values?

Using query() to Filter by Column Value in pandas DataFrame. query() function is used to filter rows based on column value in pandas. After applying the expression, it returns a new DataFrame.

Which function is used to filter rows based conditions?

Syntax. The FILTER function filters an array based on a Boolean (True/False) array. Notes: An array can be thought of as a row of values, a column of values, or a combination of rows and columns of values.


2 Answers

Here are the two main approaches. I prefer this one for its readability:

bar <- subset(foo, location == "there") 

Note that you can string together many conditionals with & and | to create complex subsets.

The second is the indexing approach. You can index rows in R with either numeric, or boolean slices. foo$location == "there" returns a vector of T and F values that is the same length as the rows of foo. You can do this to return only rows where the condition returns true.

foo[foo$location == "there", ] 
like image 181
JoFrhwld Avatar answered Sep 21 '22 18:09

JoFrhwld


Just to extend the answer above you can also index your columns rather than specifying the column names which can also be useful depending on what you're doing. Given that your location is the first field it would look like this:

    bar <- foo[foo[ ,1] == "there", ] 

This is useful because you can perform operations on your column value, like looping over specific columns (and you can do the same by indexing row numbers too).

This is also useful if you need to perform some operation on more than one column because you can then specify a range of columns:

    foo[foo[ ,c(1:N)], ] 

Or specific columns, as you would expect.

    foo[foo[ ,c(1,5,9)], ] 
like image 44
DryLabRebel Avatar answered Sep 20 '22 18:09

DryLabRebel