0

How would you write a loop to make plots for mpg vs cyl and mpg vs vs for each model on a separate plot? Thanks. PS: This is just an example data set and I have 100s of models so, definitely need a loop.

enter image description here

enter image description here

Tung
  • 26,371
  • 7
  • 91
  • 115
Jenn
  • 15
  • 7

1 Answers1

0

Not sure that is exactly what you want to achieve. Is it something like that:

data("mtcars")

library(tidyverse)

plots <- mtcars %>%
  rownames_to_column("model") %>%
  mutate(model = str_extract(model, "^[A-Za-z]+"))  %>%
  gather(key = "feature", value = "value", wt, vs) %>%
  group_by(model) %>%
  do(
    plots = ggplot(., aes(x = mpg, y = value)) +
      geom_point() +
      facet_wrap(~feature, scales = "free_y") +
      ggthemes::theme_few() +
      ggtitle(sprintf("Model: %s", .$model))
  ) %>%
  as.list()

plots <- set_names(plots[["plots"]], plots[["model"]])

plots[["Merc"]]

enter image description here

utubun
  • 4,400
  • 1
  • 14
  • 17