Home > Back-end >  Using the name "Session" gives an error in purrr::pwalk in R
Using the name "Session" gives an error in purrr::pwalk in R

Time:01-07

When I use "Session" as the name of the variable I get an error when I try to use pwalk. If I use other name like "x" instead of "Session", the error disappears. I can't understand why.

library(tidyverse)
library(ggpubr)

df <- tibble(Session = c(1, 2, 1, 2, 1, 2, 1, 2, 3),
             y = c(1, 2, 3, 1, 3, 4, 5, 3, 4))

plots <- df %>%
  group_by(Session) %>%
  nest() %>%
  mutate(plot = map(data, ~ggqqplot(., "y")),
         filename = paste0(Session, ".png")) %>%
  select(filename, plot)
#> Adding missing grouping variables: `Session`

pwalk(plots, ggsave)
#> Saving 7 x 5 in image
#> Error in `pmap()`:
#> ℹ In index: 1.
#> Caused by error in `check.options()`:
#> ! invalid argument name 'Session' in 'png_dev(..., res = dpi, units = "in")'

#> Backtrace:
#>      ▆
#>   1. ├─purrr::pwalk(plots, ggsave)
#>   2. │ └─purrr::pmap(.l, .f, ..., .progress = .progress)
#>   3. │   └─purrr:::pmap_("list", .l, .f, ..., .progress = .progress)
#>   4. │     ├─purrr:::with_indexed_errors(...)
#>   5. │     │ └─base::withCallingHandlers(...)
#>   6. │     └─ggplot2 (local) .f(...)
#>   7. │       └─ggplot2 (local) dev(...)
#>   8. │         └─grDevices (local) png_dev(..., res = dpi, units = "in")
#>   9. │           └─grDevices::check.options(new, name.opt = ".X11.Options", envir = .X11env)
#>  10. │             └─base::stop(...)
#>  11. └─base::.handleSimpleError(...)
#>  12.   └─purrr (local) h(simpleError(msg, call))
#>  13.     └─cli::cli_abort(c(i = "In index: {i}."), parent = cnd, call = error_call)
#>  14.       └─rlang::abort(...)

CodePudding user response:

You should ungroup after your mutate call. When you look at the output of plots without ungroup you can see that there is a grouped variable add like "Session" but also when using "x", to prevent this you should ungroup your data. Here is a reproducible example:

library(tidyverse)
library(ggpubr)

df <- tibble(Session = c(1, 2, 1, 2, 1, 2, 1, 2, 3),
             y = c(1, 2, 3, 1, 3, 4, 5, 3, 4))

plots <- df %>%
  group_by(Session) %>%
  nest() %>%
  mutate(plot = map(data, ~ggqqplot(., "y")),
         filename = paste0(Session, ".png")) %>%
  ungroup() %>%
  select(filename, plot) 

pwalk(plots, ggsave)

Created on 2023-01-06 with reprex v2.0.2

CodePudding user response:

Your plots tibble has 3 columns: Session, filename, and plot. When you pass that to ggsave using pwalk, ggsave passes the Session argument to the graphics device.

@Quinten shows you how to get rid of the Session column, by calling ungroup().

  • Related