I have a custom simplified function lc
to plot lc of data.
It makes a graph for every month
selected in data. I use assign
to dynamically assign each plot to a new object to be used later. I have a counter and paste0
function to help change the name using assign
in the for loop.
library(dplyr)
library(ggplot2)
library(ecotox)
df <- ecotox::lamprey_tox
lc<- function(data, dose='dose', months=c(), month='month', total='total', response='response'){
data <- data%>% filter(month %in% c(months))
counter=0
for (i in months){
counter <- counter + 1
a <- data[data$month %in% i,]
print(a)
lc <- LC_probit((response/ total) ~ log10(as.numeric(dose)), p = c(50, 90),
weights = total,
data =a)
LC50 <- lc$dose[1] #strip lc50
LC90 <- lc$dose[2] #strip lc90
assign(paste0('p', counter), ggplot(data=a,aes(x=log10(as.numeric(dose)),y=(response/total)))+
geom_point(size=4)+
geom_smooth(method="glm",
method.args=list(family=binomial(link="probit")),
aes(weight=total),colour="blue",se=TRUE, level=0.95) +
geom_segment(aes(x = log10(LC50), xend = log10(LC50), y=-Inf, yend=0.5), linetype='dashed', size=1) +
geom_segment(aes(x = -Inf, xend = log10(LC50), y=0.5, yend=0.5), linetype='dashed', size=1) +
geom_segment(aes(x = log10(LC90), xend = log10(LC90), y=-Inf, yend=0.9), linetype='dashed', size=1) +
geom_segment(aes(x = -Inf, xend = log10(LC90), y=0.9, yend=0.9), linetype='dashed', size=1))
print(p1)
}
}
However, the plot doesn’t seem to update correctly. And by print
ing inside the foor loop, it seems that when I use the counter
with assign
function, it changes the plot, but for some reason, leaves geom_segment
alone? As you can see, the geom_segment
and geom_smooth
don’t line up like they should. However…
lc(df, months=c('May', 'June', 'August'))
output:
If I change counter
to a not-dynamically changing name, like 1
, it works:
assign(paste0('p', 1), ggplot(data=a,aes(x=log10(as.numeric(dose)),y=(response/total)))+
Why is this? Thank you for any advice!