[R] for loop question in R

Kai Yang y@ngk@|9999 @end|ng |rom y@hoo@com
Wed Dec 22 19:18:56 CET 2021


 Hello Eric, Jim and Ivan,
Many thanks all of your help. I'm a new one in R area. I may not fully understand the idea from you.  I modified my code below, I can get the plots out with correct file name, but plots  are not using correct fields' name. it use y[i], and c[i] as variables' name, does not use hwy, cyl or cty, class in ggplot statement. And there is not any error message. Could you please look into my modified code below and let me know how to modify y= y[i], color = c[i] part?
Thanks,
Kai

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

    On Wednesday, December 22, 2021, 09:42:45 AM PST, Ivan Krylov <krylov.r00t using gmail.com> wrote:  
 
 On Wed, 22 Dec 2021 16:58:18 +0000 (UTC)
Kai Yang via R-help <r-help using r-project.org> wrote:

> mpg %>%    filter(hwy <35) %>%     ggplot(aes(x = displ, y = y[i],
> color = c[i])) +     geom_point()

Your code relies on R's auto-printing, where each line of code executed
at the top level (not in loops or functions) is run as if it was
wrapped in print(...the rest of the line...).

Solution: make that print() explicit.

A better solution: explicitly pass the plot object returned by the
ggplot functions to the ggsave() function instead of relying on the
global state of the program.

> ggsave("c:/temp/f[i].jpg",width = 9, height = 6, dpi = 1200, units =
> "in")

When you type "c:/temp/f[i].jpg", what do you get in return?

Use paste0() or sprintf() to compose strings out of parts.

>     [[alternative HTML version deleted]]

P.S. Please compose your messages in plain text, not HTML. See the
R-help posting guide for more info.

-- 
Best regards,
Ivan
  
	[[alternative HTML version deleted]]



More information about the R-help mailing list