Alex Thom
Alex Thom

Reputation: 39

How to allocate groups of a data frame based on time in R

Hello I have a table like so:

Entry  TimeOn TimeOff Alarm 
  1     60     70      355
  2     80     85      455
  3     100    150     400
  4     105    120     320 
  5     125    130     254
  6     135    155     220
  7     160    170     850

I would like to understand how i can group those entries so the ones starting during another alarm and ending either during another alarm or after the other alarm such as entries 4,5 & 6 can be filtered out of the data frame?

so this would be the desired result a dataframe that looked like this:

Entry  TimeOn TimeOff Alarm 
  1     60     70      355
  2     80     85      455
  3     100    150     400
  7     160    170     850

so entries 4, 5 and 6 removed

Upvotes: 2

Views: 70

Answers (1)

A. Suliman
A. Suliman

Reputation: 13125

library(dplyr)
library(data.table)
df$flag <- apply(df, 1, function(x) {
                 nrow(filter(df, data.table::between(x['TimeOn'],df$TimeOn,df$TimeOff)))
                 })

df[df$flag > 1, ]
  Entry TimeOn TimeOff Alarm flag
4     4    105     120   320    2
5     5    125     130   254    2
6     6    135     155   220    2

#Save option using Base R
df$flag <- apply(df,1,function(x) {nrow(df[x['TimeOn'] >= df$TimeOn & x['TimeOn'] <= df$TimeOff,])})

Suggested by @Andre Elrico

df[apply(df, 1, function(x) { nrow( df[between(x[['TimeOn']],df$TimeOn,df$TimeOff),] ) > 1 }),]

data

df <- read.table(text="
         Entry  TimeOn TimeOff Alarm
             1     60     70      355
             2     80     85      455
             3     100    150     400
             4     105    120     320
             5     125    130     254
             6     135    155     220
             7     160    170     850
             ",header=T)

Upvotes: 2

Related Questions