使用名称“Session”会在R中的purrr::pwalk中产生错误

bf1o4zei  于 2023-01-15  发布在  PWA
关注(0)|答案(2)|浏览(339)

当我使用“Session”作为变量名时,当我尝试使用pwalk时,我会得到一个错误。如果我使用其他名称,如“x”而不是“Session”,错误就会消失。我不明白为什么。

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(...)
nle07wnf

nle07wnf1#

调用mutate后应ungroup。查看未取消分组的图的输出时,您可以看到有一个分组变量add,如“Session”,但在使用“x”时也是如此,为防止出现这种情况,应ungroup数据。以下是一个可重现的示例:

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)

创建于2023年1月6日,使用reprex v2.0.2

ih99xse1

ih99xse12#

您的plots tibble有3列:Sessionfilenameplot。当使用pwalk将其传递给ggsave时,ggsaveSession参数传递给图形设备。
@Quinten向您展示了如何通过调用ungroup()来摆脱Session列。

相关问题