Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the first, second and last row that meets a criterion

Tags:

r

I would like to know how to extract the last row that follow a criterion. I have seen the solution for getting the first one by the function "duplicate" in the next link How do I select the first row in an R data frame that meets certain criteria?.

However is it possible to get the second or last row that meet a criterion?

I would like to make a loop for each Class (here I only put two) and select the first, second and last row that meet the criterion Weight >= 10. And if there is no row that meets the criterion to get a NA.

Finally I want to store the three values (first, second, and last row) in a list containing the values for each class.

   Class Weight
1      A     20
2      A     15
3      B     10
4      B     23
5      A     11
6      B     12
7      B     11
8      A     25
9      A      7
10     B      3
like image 658
Ruben Avatar asked Jan 31 '26 23:01

Ruben


1 Answers

Data table can help with this. This is an edit off of Davids comment to move it into the answers as his approach is the correct way to do this.

library(data.table)
DT <- as.data.table(db)
DT[Weight >= 10][, .SD[c(1, 2, .N)], by = Class]

As as faster alternative also from David look at

 indx <- DT[Weight >= 10][, .I[c(1, 2, .N)], by = Class]$V1 ; DT[indx]

Which creates the wanted index using .I and then subsets DT based on those rows.

like image 151
JWheeler Avatar answered Feb 03 '26 12:02

JWheeler



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!