Skip to content

Instantly share code, notes, and snippets.

@bhive01
Created December 23, 2016 22:26
Show Gist options
  • Select an option

  • Save bhive01/35f3f84719acf1df8da136040df07b13 to your computer and use it in GitHub Desktop.

Select an option

Save bhive01/35f3f84719acf1df8da136040df07b13 to your computer and use it in GitHub Desktop.
library(tidyverse)
df <- data.frame(Group = c(rep("A", 7), rep("B", 7), rep("C", 7)),
Time = c(rep(c(1:7), 3)),
Result = c(100, 96.9, 85.1, 62.0, 30.7, 15.2, 9.6,
10.2, 14.8, 32.26, 45.85, 56.25, 70.1, 100,
100, 55.61, 3.26, -4.77, -7.21, -3.2, -5.6))
df %>%
filter(Group != "B") %>% # filter out B because fails NLS fitting
group_by(Group) %>%
nest %>%
mutate(model = map(data, ~ lm(Result ~ Time, data = .))) %>%
mutate(model2 = map(data, ~nls(Result ~ a+(b-a)/(1+(Time/c)^d), data = ., start = c(a = -3, b = 85, c = 4, d = 10)))) %>%
ungroup() %>%
ggplot()
ggplot(data = df[df$Group == "A",], aes(x = Time, y = Result)) +
facet_wrap(~ Group) +
geom_point() +
geom_smooth(method = "nls", formula = y ~ a+(b-a)/(1+(x/c)^d), se = FALSE,
method.args = list(start = c(a = -3, b = 85, c = 4, d = 10)))
ggplot(data = df[df$Group == "B",], aes(x = Time, y = Result)) +
facet_wrap(~ Group) +
geom_point() +
geom_smooth(method = "nls", formula = y ~ a+(b-a)/(1+(x/c)^d), se = FALSE,
method.args = list(start = c(a = -3, b = 85, c = 4, d = 10)))
ggplot(data = df[df$Group =="C",], aes(x = Time, y = Result)) +
facet_wrap(~ Group) +
geom_point() +
geom_smooth(method = "nls", formula = y ~ a+(b-a)/(1+(x/c)^d), se = FALSE,
method.args = list(start = c(a = -3, b = 85, c = 4, d = 10)))
@bhive01

bhive01 commented Dec 23, 2016

Copy link
Copy Markdown
Author

Seems like part of the problem is the fact that group B fails to model with the NLS parameters supplied by OP:
https://groups.google.com/forum/#!topic/ggplot2/YgCqQX8JbPM

Eliminating this group allows the plot to complete and I believe this is what OP wants, but the starting parameters for B should be different from those in A and C. Or perhaps the data in B really can't be fit with nls(). I don't know much beyond lm() sadly.

ggplot(data = df[df$Group != "B",], aes(x = Time, y = Result)) +
  facet_wrap(~ Group) +
  geom_point() +
  geom_smooth(method = "nls", formula = y ~ a+(b-a)/(1+(x/c)^d), se = FALSE,
              method.args = list(start = c(a = -3, b = 85, c = 4, d = 10)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment