Skip to content

Instantly share code, notes, and snippets.

@TomHarrop
Last active July 24, 2018 02:34
Show Gist options
  • Save TomHarrop/1696444fafb8d7e30ba324e8c2889d2c to your computer and use it in GitHub Desktop.
Save TomHarrop/1696444fafb8d7e30ba324e8c2889d2c to your computer and use it in GitHub Desktop.
#!/usr/bin/env Rscript
library(lubridate)
library(tidyverse)
library(ggplot2)
#############
# FUNCTIONS #
#############
FindHeaderLines <- function(nd_data_lines) {
grep("^Wavelength \\(nm\\)", nd_data_lines)
}
FindSampleNames <- function(nd_data_lines,
header_lines) {
nd_data_lines[header_lines - 2]
}
FindSamplePOSIXct <- function(nd_data_lines,
header_lines) {
dmy_hms(nd_data_lines[header_lines - 1],
tz = "Pacific/Auckland")
}
FindStopLines <- function(nd_data_lines,
header_lines) {
c((header_lines - 5)[2:length(header_lines)],
length(nd_data_lines))
}
ParseNdDataLines <- function(nd_data_lines) {
# parse the metadata
my_header_lines <- FindHeaderLines(nd_data_lines)
my_stop_lines <- FindStopLines(nd_data_lines, my_header_lines)
my_sample_names <- FindSampleNames(nd_data_lines, my_header_lines)
my_sample_dates <- FindSamplePOSIXct(nd_data_lines, my_header_lines)
# read_tsv on each subset of data
my_results_list <- lapply(1:length(my_header_lines), function(i)
read_tsv(
paste(nd_data_lines[my_header_lines[[i]]:my_stop_lines[[i]]],
collapse = "\n")) %>%
mutate(Sample = my_sample_names[[i]],
Date = my_sample_dates[[i]]))
# return the full tibble
bind_rows(my_results_list)
}
########
# MAIN #
########
# read as lines
my_file <- "2018_07_20_spectra.tsv"
my_path <- normalizePath(my_file)
nd_data_lines <- read_lines(my_path)
# parse lines
nd_data_raw <- ParseNdDataLines(nd_data_lines) %>%
filter(Date > ymd_hms("2018-07-20 09:41:00", tz = "Pacific/Auckland")) %>%
mutate(Label = glue::glue("Sample {Sample}\n{Date}"))
# plot
set1 <- RColorBrewer::brewer.pal(9, "Set1")
gp <- ggplot(nd_data_raw,
aes(x = `Wavelength (nm)`,
y = `10mm Absorbance`,
group = `Label`)) +
ggtitle(my_path,
subtitle = glue::glue("Printed {now()}.")) +
theme_grey(base_size = 10) +
facet_wrap( ~ `Label`) +
geom_vline(xintercept = c(230, 260, 280),
linetype = 2,
colour = alpha(set1[2], 0.5)) +
geom_point(colour = alpha(set1[3], 0.5), shape = 16) +
geom_smooth(span = 0.25,
colour = alpha(set1[1], 0.75),
size = 1,
se = FALSE)
ggsave("plot.pdf", gp, width = 250, height = 170, units = "mm")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment