Guest User

Untitled

a guest
Nov 20th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. # the aim is to use the 'drc' package to fit models to data and then extract the data and use for plotting in ggplot
  2. # the data could be growth curves, dose-response, Michaelis-Menten etc.
  3. # here, the S.alba data from drc is used for dose-response
  4.  
  5. library(tidyverse)
  6. library(broom)
  7. library(drc)
  8. library(modelr)
  9. attach(S.alba) # the data used in this gist
  10. library(egg)
  11.  
  12. df <- S.alba
  13. # view the data in normal and log scale for dose
  14. p1 <- df %>% ggplot() + geom_point(aes(Dose, DryMatter, color = Herbicide)) + theme_bw()
  15. p2 <- df %>% ggplot() + geom_point(aes(log(Dose), DryMatter, color = Herbicide)) + theme_bw()
  16. ggarrange(p1, p2)
  17.  
  18. # define drm function to use with map
  19. drm.func <- function(x) {
  20. drm(DryMatter ~ Dose,
  21. fct = LL.4(names = c("Slope", "Lower Limit", "Upper Limit", "ED50")),
  22. data = x)
  23. }
  24.  
  25. predict.fun <- function(x) {
  26. add_predictions(data.frame(Dose = seq(0,700)), x)
  27. }
  28.  
  29. coefs.fun <- function(x) {coef(x) %>% tidy}
  30.  
  31. df2 <- df %>% group_by(Herbicide) %>% nest() %>%
  32. mutate(drmod = map(data, drm.func),
  33. pred = map(drmod, predict.fun),
  34. coefs = map(drmod, coefs.fun))
  35.  
  36. # plot raw data, model and ED50 line
  37. df2 %>% unnest(data) %>%
  38. ggplot() +
  39. geom_point(aes(log(Dose), DryMatter, color = Herbicide)) +
  40. geom_line(aes(log(Dose), pred, color = Herbicide), data =
  41. df2 %>% unnest(pred)) +
  42. geom_vline(aes(xintercept = log(x), color = Herbicide),
  43. linetype = 5,
  44. data = df2 %>% unnest(coefs) %>% filter(names == "ED50:(Intercept)")) +
  45. theme_bw()
  46.  
  47. # summary of coefficients
  48. df2 %>% unnest(coefs) %>% spread(names, x)
Add Comment
Please, Sign In to add comment