Retrieve the first, second and last line that matches the criterion

I would like to know how to extract the last row following the criterion. I have seen a solution to get the first one using the "duplicate" function in the following 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 meets the criterion?

I would like to create a loop for each Class

(I only put two here) and select the first, second and last row that match the criterion Weight >= 10

. And if there is no row that meets the criterion to get NA.

Finally, I want to store 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

      

+3


source to share


1 answer


A datasheet can help with this. This edit David's comment to move it into the answers as his approach is the correct way to do it.

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

      

As with the faster alternative, also from David see



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

      

Creates the desired index using .I and then DT subsets based on those strings.

+5


source







All Articles