Skip to content

Instantly share code, notes, and snippets.

@lukereding
Created April 2, 2018 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukereding/ad733179d61e8e26d66b4373d8a662de to your computer and use it in GitHub Desktop.
Save lukereding/ad733179d61e8e26d66b4373d8a662de to your computer and use it in GitHub Desktop.
require(tidyverse)
# computes things you want to know across the entire trial
do_it <- function(x) {
name <- x$filename[1]
fish_name <- name %>% stringr::str_match(pattern = "_S[a-z]+?_([A-Za-z]+)_") %>% as.vector %>% .[2]
temp <- x %>%
mutate(time_zone = lead(time) - time) %>%
group_by(code) %>%
summarise(total = sum(time_zone, na.rm = TRUE)) %>%
spread(code, total)
temp$transits <- nrow(x)
temp$filename <- name
temp$name = stringr::str_replace_all(string = fish_name, pattern ="[//_]", "")
temp
}
# computes things you want to know for each half
do_it_with_halves <- function(x) {
name <- x$filename[1]
fish_name <- name %>% stringr::str_match(pattern = "_S[a-z]+?_([A-Za-z]+)_") %>% as.vector %>% .[2]
total_time <- x$time[length(x$time)]
half_time <- round(total_time / 2, 1)
if(!half_time %in% x$time){
# find the right index to add it to the dataframe
idx <- max(which(x$time < half_time))
x <- add_row(x, time = half_time, class = 1, code = x$code[idx], .after = idx) %>%
mutate(half = if_else(time < half_time, "first_half", "second_half"))
}
temp <- x %>%
mutate(time_zone = lead(time) - time) %>%
group_by(code, half) %>%
summarise(total = sum(time_zone, na.rm = TRUE)) %>%
spread(code, total)
temp$transits <- c(filter(x, half == "first_half") %>% nrow, filter(x, half == "second_half") %>% nrow)
temp$filename <- name
temp$name = stringr::str_replace_all(string = fish_name, pattern ="[//_]", "")
temp
}
path <- "path/to/your/cowlog/files"
scototaxis <- dir(path, pattern = "*.csv", full.names = TRUE) %>%
set_names %>%
map(read_csv) %>%
imap(~ transform(.x, filename = .y)) %>%
map(do_it_with_halves) %>%
Reduce(bind_rows, .)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment