Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching a Data Frame in R

How do I go about searching a data.frame based on multiple criteria? For instance, I have a data.frame with columns such as Date, Time, Item, Value, and I then want to search the data.frame where I have Date = 1/2/2010, Time = 5pm, Item = Car, Value = 5, is there a function that will allow me to do that? More importantly, how do I obtain the row index of the data frame which has these values?

For example, say all these values are in the third row of the data frame, is there a function which will search the data frame row by row and then output that index is 3?

like image 851
ThePlowKing Avatar asked Oct 28 '25 17:10

ThePlowKing


1 Answers

Sounds like you have a question about performing a query. If you are familiar with dplyr package, you'll find functions such as select that can help. However, you should be able accomplish what you need just by using the base and stats packages.

For instance, given a data frame, you should extract the row indices that match your criteria. You can accomplish this by using the which function:

indices <- which(data$Date == "1/2/2010" & data$Time == "5pm" & data$Item =="Car" & data$Value == 5)

Then you'd be ready to subset

data_subset <- data[indices, ]

I hope the above hypothetical example would help you get to the answer you need.

like image 152
David C. Avatar answered Oct 31 '25 07:10

David C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!