For some reason, I can't figure out, why when I run a ggplot
loop to create multiple graphs I don't see them in the environment and hence can't further display the graphs.
Data sample.
db = data.frame(exposure = sample(1:100, 100),
exposure2 = sample(-90:100,100),
outcome = sample(200:1000,100))
exposure_vector = c("exposure","exposure2")
exposure_title = c("Pesticide","Apple")
for (i in 1:length(exposure_vector)) {
current_exposure = db[[exposure_vector[i]]]
title = exposure_title[i]
graph_name = paste0(title,"_","Graph")
graph_name=ggplot(db,aes(x=current_exposure,y=outcome)) geom_smooth()
theme_bw() ylab("outcome") xlab("exposure") ggtitle(title)
print(graph_name)
}
CodePudding user response:
The graphname
is out of scope.
You need to declare it outside the loop.
For example
db = data.frame(exposure = sample(1:100, 100),
exposure2 = sample(-90:100,100),
outcome = sample(200:1000,100))
exposure_vector = c("exposure","exposure2")
exposure_title = c("Pesticide","Apple")
plot <- list() #declare
for (i in 1:length(exposure_vector)) {
current_exposure = db[[exposure_vector[i]]]
title = exposure_title[i]
graph_name = paste0(title,"_","Graph")
graph_name=ggplot(db,aes(x=current_exposure,y=outcome)) geom_smooth()
theme_bw() ylab("outcome") xlab("exposure") ggtitle(title)
plot[[i]] <- graph_name #write
print(graph_name)
}
CodePudding user response:
I assume that you want to assign to a variable, whose name is paste0(title, "_", "Graph")
, the value of the plot. If this is correct, you should use assign
library(ggplot2)
db <- data.frame(exposure = sample(1:100, 100),
exposure2 = sample(-90:100,100),
outcome = sample(200:1000,100))
exposure_vector <- c("exposure","exposure2")
exposure_title <- c("Pesticide","Apple")
for (i in 1:length(exposure_vector)) {
current_exposure <- db[[exposure_vector[i]]]
title <- exposure_title[i]
graph_name <- paste0(title,"_","Graph")
p <- ggplot(db,aes(x=current_exposure,y=outcome))
geom_smooth()
theme_bw()
ylab("outcome")
xlab("exposure")
ggtitle(title)
assign(graph_name, p)
print(p)
}
ls()
##> [1] "Apple_Graph" "current_exposure" "db" "exposure_title"
##> [5] "exposure_vector" "graph_name" "i" "p"
##> [9] "Pesticide_Graph" "title"
CodePudding user response:
This is probably a better way to do what you are trying to do. You can mapply
over your vectors of titles and exposures, which will return a list
of graphs you can then refer to by name:
graphs <- mapply(X=exposure_title,Y=exposure_vector, function(X,Y){
ggplot(db,aes(x=get(Y),y=outcome))
geom_smooth()
theme_bw()
ylab("outcome")
xlab("exposure")
ggtitle(X)
}, SIMPLIFY = FALSE )
graphs$Pesticide
graphs$Apple