Home > Mobile >  Why does my for loop in R only saves the last iteration?
Why does my for loop in R only saves the last iteration?

Time:06-15

I am trying to save differents plots in this vector but it saves me the last iteration in all the cases. The extrange thing is that the title change as it should. Thanks!

pl1=vector("list",5)
for (i in 1:5) {
  pl1[[i]]=ggplot() geom_point(aes(x=c(1:96),y=G1[[i]]),color="blue") 
    scale_x_continuous(breaks =seq(0, 24, 3),expand = c(0,0)) 
    scale_y_continuous(breaks =seq(1, 8, 0.8)) 
    labs(title=ubi[i,3],x="Dias(hs)",y= "Pp(mm/hs)") 
    theme_bw() theme(panel.grid = element_line(color="white"))
  }

CodePudding user response:

You may use local and print.

for (i in 1:5) {
 
  pl1[[i]] <- local({ 
    i <- i
    p1 <- ggplot() geom_point(aes(x=c(1:96),y=G1[[i]]),color="blue") 
      scale_x_continuous(breaks =seq(0, 24, 3),expand = c(0,0)) 
      scale_y_continuous(breaks =seq(1, 8, 0.8)) 
      labs(title=ubi[i,3],x="Dias(hs)",y= "Pp(mm/hs)") 
      theme_bw() theme(panel.grid = element_line(color="white"))
    print(p1)})
}
  • Related