Skip to content

Instantly share code, notes, and snippets.

@davebraze
Last active March 6, 2018 15:46
Show Gist options
  • Save davebraze/fefc1f470150775180e71c2e1e4e80ac to your computer and use it in GitHub Desktop.
Save davebraze/fefc1f470150775180e71c2e1e4e80ac to your computer and use it in GitHub Desktop.
Convert wide format fixation report to long format samples
library(tidyverse)
## toy fixation report
fixations <- tibble(fixidx=as.integer(1:3), start=c(100,250,372), end=c(202, 348, 426),
x=sample(0:1000,3), y=sample(0:1000,3))
## convert to long format
fixations <- fixations %>%
gather(start, end, -c(fixidx,x,y)) %>%
arrange(fixidx) %>%
rename(event=start, time=end)
## assume 500hz sample rate
samples <- tibble(time=seq(min(fixations$time), max(fixations$time), by=2))
## expand events to samples and do some fixup
sample_report <- samples %>% left_join(fixations, "time") %>%
fill(fixidx, event, x, y) %>%
group_by(fixidx,event) %>%
mutate(evt=ifelse(row_number()==1, "start",event)) %>%
ungroup() %>%
mutate(x=ifelse(evt=="start", x, NA), y=ifelse(evt=="start", y, NA),
event=ifelse(evt=="start", "fixation", NA)) %>%
select(-evt)
## In the event that there are multiple trials in a data.frame, then things are a bit more complicated.
## It becomes necessary to compute sample vectors on a per-trial basis.
## The left_join then looks like: " left_join(report_l, c("TRIAL_INDEX", "time")) %>% "
trials <- tibble(idx = 1:3, stime = 2, etime = c(20,40,30))
samples <- trials %$%
map2(stime, etime, seq, by=2) %>%
map(data.frame) %>%
map(rename_all, function(x) "time") %>%
bind_rows(.id="TRIAL_INDEX")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment