Nata
Nata

Reputation: 171

How to subset by time range?

I would like to create a subset from the following example of data frame. The condition is to select those rows where time column values belong to time range from the minimum time for the certain id till the next lets say one hour.

    id    time
    1   1468696537          
    1   1468696637          
    1   1482007490          
    2   1471902849          
    2   1471902850          
    2   1483361074          
    3   1474207754          
    3   1474207744          
    3   1471446673          
    3   1471446693  

And the output should be like this:

   id    time
    1   1468696537          
    1   1468696637          
    2   1471902849          
    2   1471902850          
    3   1471446673          
    3   1471446693  

Please, help me how to do that?

Upvotes: 1

Views: 140

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50678

We can do the following:

library(magrittr);
library(dplyr);
df %>%
    group_by(id) %>%
    filter(time <= min(time) + 3600)
#     id       time
#  <int>      <int>
#1     1 1468696537
#2     1 1468696637
#3     2 1471902849
#4     2 1471902850
#5     3 1471446673
#6     3 1471446693

Explanation: Group entries by id, then filter entries that are within min(time) + 1 hour.


Sample data

df <- read.table(text =
    "   id    time
    1   1468696537
    1   1468696637
    1   1482007490
    2   1471902849
    2   1471902850
    2   1483361074
    3   1474207754
    3   1474207744
    3   1471446673
    3   1471446693  ", header = T)

Upvotes: 2

Related Questions