简体   繁体   中英

Rename objects in for loop in R

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!

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM