Reputation: 57
Some brief guidance if possible while learning R:
Created for
loop drawing a set of histograms:
for ( i in 1:10) {
p <- ggplot(data, aes(x=data[,i], fill=Group)) +
geom_histogram(binwidth=200, alpha=.5, position="dodge")
print(p)
p[i] <- p
}
I would like to assign different names to p
to call these plots separately later on. I would have thought adding p[i] <- p
would have been sufficient.
What is the mistake I am making? Thanks all!
Upvotes: 3
Views: 6200
Reputation: 13827
Another option is to use assign
for ( i in 1:10) {
assign(paste0("plot", i), ggplot(data, aes(x=data[,i], fill=Group)) +
geom_histogram(binwidth=200, alpha=.5, position="dodge") )
}
This will create each plot as a different object (plot1
, plot2
, plot3
... ) in your global environment
Upvotes: 3
Reputation: 4532
your first assignment to p from ggplot reset p each time and your p[i] <-p
cannot work as it is the same object on both sides of the assignment. You want to use:
pList <- list()
for ( i in 1:10) {
p <- ggplot(data, aes(x=data[,i], fill=Group)) +
geom_histogram(binwidth=200, alpha=.5, position="dodge")
print(p)
pList[[i]] <- p
}
Then you can access the different plots as p[[1]]
etc.
Upvotes: 4