[R] question about for loop

Kai Yang y@ngk@|9999 @end|ng |rom y@hoo@com
Sat Dec 25 01:41:29 CET 2021


 Thanks Andrew. This is super helpful. --- Kai
    On Friday, December 24, 2021, 02:37:14 PM PST, Andrew Simmons <akwsimmo using gmail.com> wrote:  
 
 y, c, and f only exist in the context of mac2If you want to use them, you'll have to write mac2$y, mac2$c, or mac2$f (or the [[ versions mac2[["y"]], mac2[["c"]], or mac2[["f"]])Combining that with index i would then look like mac2$y[[i]] or mac2[[i, "y"]]
Also, I think you want to use aes_string instead of aes (since you want those expressions within aes to be evaluated)Something like this seems to work for me:

`%>%` <- magrittr::`%>%`


writeLines(FILE <- tempfile(), text =
r"{y,c,f
hwy,cyl,hwy_cyl2
cty,class,cty_class2}")


mac2 <- readr::read_csv(FILE)
for (i in seq_len(nrow(mac2))) {
    ggplt <- ggplot2::mpg %>%
        dplyr::filter(hwy < 35) %>%
        ggplot2::ggplot(
            ggplot2::aes_string(
                x = "displ",
                y = mac2[[i, "y"]],
                color = mac2[[i, "c"]]
            )
        ) +
        ggplot2::geom_point() +
        ggplot2::ylab(mac2[[i, "y"]]) +
        ggplot2::guides(
            color = ggplot2::guide_legend(title = mac2[[i, "c"]])
        )
    ggplot2::ggsave(
        filename = tempfile(
            mac2[[i, "f"]],
            fileext = ".jpg"
        ),
        plot = ggplt,
        width = 9, height = 6, dpi = 1200
    )
}


unlink(FILE)


runs fine on my computer, but might look more like this for you:

library(magrittr)
library(ggplot2)
library(dplyr)
library(readr)


mac2 <- read_csv("C:/temp/mac2.csv")
for (i in seq_len(nrow(mac2))) {
    ggplt <- mpg %>%
        filter(hwy < 35) %>%
        ggplot(
            aes_string(
                x = "displ",
                y = mac2[[i, "y"]],
                color = mac2[[i, "c"]]
            )
        ) +
        geom_point() +
        ylab(mac2[[i, "y"]]) +
        guides(
            color = guide_legend(title = mac2[[i, "c"]])
        )
    ggsave(
        filename = paste0("C:/temp/", mac2[[i, "f"]], ".jpg"),
        plot = ggplt,
        width = 9, height = 6, dpi = 1200
    )
}


try reading through aes and aes_string, and keep in mind that columns in data frames aren't R variables (where they are in Excel). If you want to use columns like they are variables, you can try using `with`. For example:

library(magrittr)
library(ggplot2)
library(dplyr)
library(readr)


mac2 <- read_csv("C:/temp/mac2.csv")
for (i in seq_len(nrow(mac2))) {
    with(mac2[i, ], {
        ggplt <- mpg %>%
            filter(hwy < 35) %>%
            ggplot(
                aes_string(
                    x = "displ",
                    y = y,
                    color = c
                )
            ) +
            geom_point() +
            ylab(y) +
            guides(
                color = guide_legend(title = c)
            )
        ggsave(
            filename = paste0("C:/temp/", f, ".jpg"),
            plot = ggplt,
            width = 9, height = 6, dpi = 1200
        )
    })
}




On Fri, Dec 24, 2021 at 4:48 PM Kai Yang via R-help <r-help using r-project.org> wrote:

Hello Team,
I create a csv file (mac2) to save parameter values. the file looks like:

y,c,f
hwy,cyl,hwy_cyl2
cty,class,cty_class2

Then I load the file into R and apply the parameters y, c, f in for loop, see my code below:
library(ggplot2)
library(tidyverse)
library(readr)
mac2 <- read_csv("C:/temp/mac2.csv")
View(mac2)
for (i in seq(nrow(mac2))){
  mpg %>%
    filter(hwy <35) %>% 
    ggplot(aes(x = displ, y = get(y[i]), color = get(c[i]) )) + 
    geom_point()+
    ylab(y[i]) +                              
    guides(color = guide_legend(title = c[i]))    ggsave(paste0("c:/temp/",f[i],".jpg"),width = 9, height = 6, dpi = 1200, units = "in")
}

but I got an error message: "Error in dots_list(..., title = title, subtitle = subtitle, caption = caption,  :  object 'y' not found"
Does anyone know how to fix the problem?
Thanks,
Kai


        [[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.

  
	[[alternative HTML version deleted]]



More information about the R-help mailing list