[R] for loop question in R

jim holtman jho|tm@n @end|ng |rom gm@||@com
Wed Dec 22 18:27:33 CET 2021


You may have to add an explicit 'print' to ggplot

library(ggplot2)
library(tidyverse)
y <- c("hwy","cty")
c <- c("cyl","class")
f <- c("hwy_cyl","cty_class")
mac <- data.frame(y,c,f)
for (i in nrow(mac)){
  mpg %>%    filter(hwy <35) %>%
     print(ggplot(aes(x = displ, y = y[i], color = c[i])) +     geom_point())
  ggsave("c:/temp/f[i].jpg",width = 9, height = 6, dpi = 1200, units = "in")
}

Thanks

Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.


Thanks

Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.


On Wed, Dec 22, 2021 at 9:08 AM Kai Yang via R-help
<r-help using r-project.org> wrote:
>
> Hello R team,I want to use for loop to generate multiple plots with 3 parameter, (y is for y axis, c is for color and f is for file name in output). I created a data frame to save the information and use the information in for loop. I use y[i], c[i] and f[i] in the loop, but it seems doesn't work. Can anyone correct my code to make it work?
> Thanks,Kai
>
> library(ggplot2)library(tidyverse)
> y <- c("hwy","cty")c <- c("cyl","class")f <- c("hwy_cyl","cty_class")
> mac <- data.frame(y,c,f)
> for (i in nrow(mac)){  mpg %>%    filter(hwy <35) %>%     ggplot(aes(x = displ, y = y[i], color = c[i])) +     geom_point()  ggsave("c:/temp/f[i].jpg",width = 9, height = 6, dpi = 1200, units = "in")}
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list