Guest User

Untitled

a guest
Jul 22nd, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. #!/usr/bin/env Rscript
  2.  
  3. library(lubridate)
  4. library(tidyverse)
  5. library(ggplot2)
  6.  
  7. #############
  8. # FUNCTIONS #
  9. #############
  10.  
  11. FindHeaderLines <- function(nd_data_lines) {
  12. grep("^Wavelength \\(nm\\)", nd_data_lines)
  13. }
  14.  
  15. FindSampleNames <- function(nd_data_lines,
  16. header_lines) {
  17. nd_data_lines[header_lines - 2]
  18. }
  19.  
  20. FindSamplePOSIXct <- function(nd_data_lines,
  21. header_lines) {
  22. dmy_hms(nd_data_lines[header_lines - 1],
  23. tz = "Pacific/Auckland")
  24. }
  25.  
  26. FindStopLines <- function(nd_data_lines,
  27. header_lines) {
  28. c((header_lines - 5)[2:length(header_lines)],
  29. length(nd_data_lines))
  30. }
  31.  
  32. ParseNdDataLines <- function(nd_data_lines) {
  33. # parse the metadata
  34. my_header_lines <- FindHeaderLines(nd_data_lines)
  35. my_stop_lines <- FindStopLines(nd_data_lines, my_header_lines)
  36. my_sample_names <- FindSampleNames(nd_data_lines, my_header_lines)
  37. my_sample_dates <- FindSamplePOSIXct(nd_data_lines, my_header_lines)
  38. # read_tsv on each subset of data
  39. my_results_list <- lapply(1:length(my_header_lines), function(i)
  40. read_tsv(
  41. paste(nd_data_lines[my_header_lines[[i]]:my_stop_lines[[i]]],
  42. collapse = "\n")) %>%
  43. mutate(Sample = my_sample_names[[i]],
  44. Date = my_sample_dates[[i]]))
  45. # return the full tibble
  46. bind_rows(my_results_list)
  47. }
  48.  
  49. ########
  50. # MAIN #
  51. ########
  52.  
  53. # read as lines
  54. my_file <- "2018_07_20_spectra.tsv"
  55. my_path <- normalizePath(my_file)
  56. nd_data_lines <- read_lines(my_path)
  57.  
  58. # parse lines
  59. nd_data_raw <- ParseNdDataLines(nd_data_lines) %>%
  60. filter(Date > ymd_hms("2018-07-20 09:41:00", tz = "Pacific/Auckland")) %>%
  61. mutate(Label = glue::glue("Sample {Sample}\n{Date}"))
  62.  
  63.  
  64. # plot
  65. set1 <- RColorBrewer::brewer.pal(9, "Set1")
  66. gp <- ggplot(nd_data_raw,
  67. aes(x = `Wavelength (nm)`,
  68. y = `10mm Absorbance`,
  69. group = `Label`)) +
  70. ggtitle(my_path,
  71. subtitle = glue::glue("Printed {now()}.")) +
  72. theme_grey(base_size = 10) +
  73. facet_wrap( ~ `Label`) +
  74. geom_vline(xintercept = c(230, 260, 280),
  75. linetype = 2,
  76. colour = alpha(set1[2], 0.5)) +
  77. geom_point(colour = alpha(set1[3], 0.5), shape = 16) +
  78. geom_smooth(span = 0.25,
  79. colour = alpha(set1[1], 0.75),
  80. size = 1,
  81. se = FALSE)
  82.  
  83. ggsave("plot.pdf", gp, width = 250, height = 170, units = "mm")
Add Comment
Please, Sign In to add comment