1

I need to loop over files and then create for each file an object:

Here is an example :

filenames <- Sys.glob("/Users/Desktop/*.nwk")
for (i in filenames ) {
  print(paste0("Processing the phylogeny: ",i))
    p <- a code that generate a figure 
}

And then I generate 5 figures that I call with this code :

multiplot(p1,p2,p3,p4,p5 ncol=2, labels=c('A', 'B','C','D','E'))

But I wondered how can I call assign the 1,2 etc values into the variable objects p?

I tried to create a nb=1 object and then assign as p+nb <- a code that generate a figure, but it does not work

3 Answers 3

2

There are dedicated packages for plotting/merging multiple plots. patchwork, cowplot, grid, egg, etc.

Use lapply to generate ggplot objects in a list, then use cowplot::plot_grid, something like:

cowplot::plot_grid(
  plotlist = lapply(list.files(...), function(i){
    #import file
    d <- read.table(i)
    #plot
    ggplot(d, aes(...)) + geom_...
  }),
  ncol = 2)
Sign up to request clarification or add additional context in comments.

Comments

1

You can do that but I'll suggest not to create 5 plot objects in global environment. Store the output of plots in a list.

list_plot <- vector('list', length(filenames))

for (i in seq_along(filenames)) {
  cat("\nProcessing the phylogeny: ",filenames[i])
  list_plot[[i]] <- a code that generate a figure using filenames[i] to read file
}

do.call(multiplot, c(list_plot, ncol=2, labels=c('A', 'B','C','D','E')))

Comments

-1

I found a way by doing :

Phylo_name<-paste0("p",nb,sep="")
  eval(call("<-", as.name(Phylo_name), ggtree(tr = phylo,
                                              mapping = aes(color = group)) + geom_tiplab() + theme(legend.position="right")+ 
              scale_color_manual(values=color_vector)))

1 Comment

You are much better off using assign() rather than this eval(call("<-"), ....) setup. But even better don't create a bunch of loose variables in your global namespace. You can easily stick all these values in a list with lapply or purrr::map. I'm not sure which multiplot() function you are using but it probably has a parameter that takes a list of plots.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.