Ruben
Ruben

Reputation: 493

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

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

Upvotes: 3

Views: 1690

Answers (1)

JWheeler
JWheeler

Reputation: 320

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.

Upvotes: 5

Related Questions