/
pupil_bin.R
48 lines (41 loc) · 1.36 KB
/
pupil_bin.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#' Bin pupil data
#'
#' Bin pupil data into smaller time-bins. This is useful to perform time-series
#' analyses or to just reduce the size of the data. See
#' https://dr-jt.github.io/pupillometry/ for more information.
#'
#' @section Output:
#'
#' Reduces the number of rows into discrete time-bins. Changes the values in
#' Time and pupil columns.
#'
#' @param x dataframe.
#' @param bin_length Length of bins in milliseconds.
#' @import data.table
#' @export
#'
pupil_bin <- function(x, bin_length = NULL){
bin <- function(x, bin_length) {
x <- dplyr::group_by(x, Subject, Trial, add = TRUE)
x <- dplyr::mutate(x,
TimeBin = trunc(Time / bin_length),
TimeBin = ifelse(Time < 0, TimeBin - 1, TimeBin),
Time = TimeBin * bin_length)
x <- dplyr::group_by(x, TimeBin, add = TRUE)
x <- dplyr::mutate(x, pupil_val = mean(pupil_val, na.rm = TRUE))
x <- dplyr::ungroup(x)
x <- dplyr::select(x, -TimeBin)
x <- dplyr::distinct(x, Subject, Trial, Time, .keep_all = TRUE)
}
x <- dplyr::as_tibble(x)
eyes <- eyes_detect(x)
for (eye in eyes) {
real_name <- eye
colnames(x)[which(colnames(x) == real_name)] <- "pupil_val"
x <- dtplyr::lazy_dt(x)
x <- bin(x, bin_length)
x <- dplyr::as_tibble(x)
colnames(x)[which(colnames(x) == "pupil_val")] <- real_name
}
return(x)
}