Adela Iliescu
Adela Iliescu

Reputation: 303

How to group data by intervals of seconds?

I have some events that I need grouped by 2 seconds intervals for each trial and I am not sure how to do this.

event<- c('tr_start', 'mag', 'lev', 'lev', 'lev', 'mag',
'tr_start', 'mag','mag', 'lev', 'lev', 'lev', 'mag', 'mag') 
time<- c(6, 7, 8.5, 10.2, 11, 14, 14.5, 15.1, 16, 16.2, 17, 17.7,  18, 18.1)
trial<- c(rep(1, 6), rep(2,8))
df<- cbind(event, time, trial)

The times is in seconds. The expected output would be with a new column 'value' with a sum of number of events of each type ('mag' or 'lev') and the starting time for each trial is defined by the event 'tr_start'.

This is the desired output for trial 1: The trial starts at 6s (set by 'tr_start' event). That means that there are 3 intervals of 2 seconds until trial 2 (6-8, 8-10, 10-12). The output should just count the number of 'mag' and 'lev' that occurred in each inteval of 2 second.

 event<- c('mag', 'lever',  'mag', 'lever', 'mag', 'lever')
 trial<- c(rep(1, 6))
 value<- c(1, 1, 0, 1, 1, 1)
 df_summarry<- cbind(event, trial, value) 

Thanks!

Upvotes: 0

Views: 46

Answers (1)

GKi
GKi

Reputation: 39717

Maybe something like:

df <- as.data.frame(df)
df$time  <- as.numeric(levels(df$time))[df$time]

tapply(seq_len(nrow(df)), df$trial, function(x) {
  tt  <- (df$time[x[-1]] - df$time[x[1]])  %/% 2 * 2
  tt <- factor(tt, levels=seq(0,max(tt),2))
  tt <- t(table(df$event[x[-1]], tt)[1:2,])
  data.frame(tStart = df$time[x[1]]+as.numeric(rownames(tt)), tEnd = 2+df$time[x[1]]+as.numeric(rownames(tt)), lev=tt[,1], mag=tt[,2])
})
#$`1`
#  tStart tEnd lev mag
#0      6    8   0   1
#2      8   10   1   0
#4     10   12   2   0
#6     12   14   0   0
#8     14   16   0   1
#
#$`2`
#  tStart tEnd lev mag
#0   14.5 16.5   1   2
#2   16.5 18.5   2   2

Upvotes: 1

Related Questions