ant ant - 2 months ago 6
R Question

How to see n rows after a specific row

I'm trying to track user actions but I'd like to see what they do AFTER a specific event. How do I get the next n amount of lines?

For example below, I'd like to know what the user is doing after they "Get mushroom" to see if they are eating it. I'd want to reference the "Get mushroom" for each User and see the next few lines after that.

User Action
Bob Enter chapter 1
Bob Attack
Bob Jump
Bob Get mushroom
Bob Open inventory
Bob Eat mushroom
Bob Close inventory
Bob Run
Mary Enter chapter 1
Mary Get mushroom
Mary Attack
Mary Jump
Mary Attack
Mary Open inventory
Mary Close inventory


I'm not sure how to approach this after grouping by users. Expected results would be something like the below if i wanted 3 lines below

User Action
Bob Get mushroom # Action I want to find and the next 3 lines below it
Bob Open inventory
Bob Eat mushroom
Bob Close inventory
Mary Get mushroom # Action I want to find and the next 3 lines below it
Mary Attack
Mary Jump
Mary Attack


Thank you.

Answer

Two alternatives with dplyr and data.table:

library(dplyr)
df1 %>% 
  group_by(User) %>% 
  slice(rep(which(Action == 'Get-mushroom'), each=4) + 0:3)

library(data.table)
setDT(df1)[df1[, rep(.I[Action == 'Get-mushroom'], each=4) + 0:3, User]$V1]

both result in:

   User          Action
1:  Bob    Get-mushroom
2:  Bob  Open-inventory
3:  Bob    Eat-mushroom
4:  Bob Close-inventory
5: Mary    Get-mushroom
6: Mary          Attack
7: Mary            Jump
8: Mary          Attack