0
votes

I have data that looks something like this:

time level     strain
   <dbl> <dbl>      <chr>
 1   0.0 0.000 M12-611020
 2   1.0 0.088 M12-611020
 3   3.0 0.211 M12-611020
 4   4.0 0.278 M12-611020
 5   4.5 0.404 M12-611020
 6   5.0 0.606 M12-611020
 7   5.5 0.778 M12-611020
 8   6.0 0.902 M12-611020
 9   6.5 1.024 M12-611020
10   8.0 1.100 M12-611020
11   0.0 0.000 M12-611025
12   1.0 0.077 M12-611025
13   3.0 0.088 M12-611025
14   4.0 0.125 M12-611025
15   5.0 0.304 M12-611025
16   5.5 0.421 M12-611025
17   6.0 0.518 M12-611025
18   6.5 0.616 M12-611025
19   7.0 0.718 M12-611025

I can easily graph it using ggplot, asking ggplot to look at the strains seperatley and using stat_smooth to fit a curve:

ggplot(data = data, aes(x = time, y = level), group = strain) + stat_smooth(aes(group=strain,fill=strain, colour = strain) ,method = "loess", se = F, span = 0.8) + 
      theme_gray()+xlab("Time(h)") + 
      geom_point(aes(fill=factor(strain)),alpha=0.5 , size=3,shape = 21,colour = "black", stroke = 1)+
      theme(legend.position="right")

enter image description here

I would then like to predict using the loess curve that was fitted to I do so as follows:

# define the model
model <- loess(time ~ strain,span = 0.8, data = data)

# Predict for given levle (x) the time (y)
predict(model, newdata = 0.3, se = FALSE)

I do not know however to predict for one or other of my "strains" set out above (i.e the red or blue lines in the plot)?

Additionally is there a simple way to plot this predicytion on the graph for exmaple in the form of a dotted line going across at 0.3 down to the predicted time as above?

1

1 Answers

1
votes

Do you mean something like this?

p <- ggplot(data = dat, aes(x = time, y = level, fill = strain)) + 
  geom_point(alpha=0.5 , size=3,shape = 21, colour = "black", stroke = 1) +
  stat_smooth(aes(group=strain, colour=strain) ,method = "loess", se = F, span = 0.8)


newdat <- split(dat, dat$strain)
mod <- lapply(newdat, function(x)loess(level ~ time,span = 0.8, data = x))  

predict(mod[["M12-611020"]], newdata = 2, se = FALSE)

p + 
  geom_segment(aes(x=2, xend=2, y=0, yend=0.097), linetype="dashed") + 
  geom_segment(aes(x=0, xend=2, y=0.097, yend=0.097), linetype="dashed")

enter image description here