简体   繁体   中英

R - Multiple for loop to produce and save plots

I am trying to produce several R plots (outputs of the "vegan" package) using several for loop condition to subset my dataset. If I only use one for condition, I will retrieve the plots that I want but if I chain the for loops, it will not create the number of expected conditions.

My data frame is similar to:

my_df<- data.frame(Cruise = sample(c("cruise2016" ,"cruise2008" ,"cruise2012" ,"cruise2014" ,"cruise2011"), 50, replace=T),
                Depth_interval = sample(c("100","200","500"), 50, replace = T),
                data.frame(matrix(sample(1:100,300,replace=T), nrow=50)))

I use two lists as conditions for the loops:

cruise.list <- unique(my_df$Cruise)
interval.list <- unique(my_df$Depth_interval)

With these lists, I would like to plot all the depth intervals (3 uniques) within each cruise (5 uniques)

for (i in seq_along(cruise.list)) {

  for (i in seq_along(interval.list)) {

    pdf(paste("my_path",
              cruise.list[i],
              interval.list[i],
              ".pdf", sep=""))

    df <- my_df %>%

      filter(
        Cruise == cruise.list[i],
        Depth_interval == interval.list[i])

    df.nmds <- metaMDS(df, trymax = 1000, k = 3, distance = "bray")

    # Plot 
    ordiplot(df.nmds, disp="sites", type="p", cex.lab=1.3)
    title(main=paste(cruise.list[i], "\n", interval.list[i],"\n", "stress : ", round(df.nmds$stress,2),sep=""), cex.main=1.5)

    dev.off()

  }

}

With this code, I only get 3 plots rather than the 15 expected. I guess that the for loops are order in a way that R does not read the conditions as I expect.

Thanks for any help,

Bests

You have used the same "looping variable" in both loops. For loops work by assigning the current value of the sequence to the variable you specify, so in your nested loops, first the current cruise gets assigned to i , and then immediately after, i gets overwritten with the current interval, and you have no way of accessing the current cruise anymore, eg:

cruise_list = c("Princess", "White Star")
interval_list = c("Summer", "winter")

for (i in cruise_list) {
    print(paste("Outer loop: i =", i))
    for (i in interval_list) {
        print(paste("Inner loop: i =", i))
    }
}
[1] "Outer loop: i = Princess"
[1] "Inner loop: i = Summer"
[1] "Inner loop: i = winter"
[1] "Outer loop: i = White Star"
[1] "Inner loop: i = Summer"
[1] "Inner loop: i = winter"

Also note that you can iterate directly over vectors like cruise_list as I've done above without going through seq_along and generating indexes, doing it directly like that might have helped you notice the problem sooner.

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