You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用`purrr::pwalk`保存嵌套数据框列表列中的ggplot时遭遇“unused argument”错误

purrr::pwalk保存嵌套数据框列表列中的ggplot时遭遇“unused argument”错误

我来帮你搞定这个问题~你遇到的错误其实很好理解:pwalk的特性是会把数据框的所有列都作为参数传递给你定义的函数,但你写的函数只接收cyl和plots两个参数,而你的cyl_mtcars数据框还有第三列data,所以pwalk会把data也塞给函数,函数就懵了——“这参数我没接收啊”,于是就抛出了unused argument的错误。

给你两种简单的解决办法,任选其一就行:

方法1:只传递需要的列给pwalk

在调用pwalk之前,先用select把cyl和plots这两列单独挑出来,这样pwalk就不会把多余的data列传进去了:

cyl_mtcars %>%
  select(cyl, plots) %>% # 只保留需要的两列
  pwalk(
    function(cyl, plots) {
      ggsave(filename = file.path(temp_dir, glue("{cyl}.png")), plot = plots)
    }
  )

方法2:用...接收多余的参数

如果你不想筛选列,也可以在函数定义里加个...,它会帮你“吃掉”所有多余的参数,避免报错:

cyl_mtcars %>%
  pwalk(
    function(cyl, plots, ...) { # 用...接收多余的data参数
      ggsave(filename = file.path(temp_dir, glue("{cyl}.png")), plot = plots)
    }
  )

另外提醒一下,你的原代码里漏加载了几个必要的包:purrr(用于map和pwalk)、ggplot2(用于绘图和ggsave)、glue(用于拼接文件名),记得提前加载哦。这里给你一份完整的可运行代码:

data("mtcars")
temp_dir <- tempfile()
dir.create(temp_dir)

library(tidyr)
library(purrr)
library(ggplot2)
library(glue)

plot_fun <- function(x){
  p <- ggplot(data = x, aes(x = wt, y = mpg)) +
    geom_point()
  return(p)
}

cyl_mtcars <- mtcars %>%
  nest(data = -cyl) %>%
  mutate(plots = map(.x = data, .f = plot_fun))

# 任选一种方法运行即可
# 方法1
cyl_mtcars %>%
  select(cyl, plots) %>%
  pwalk(
    function(cyl, plots) {
      ggsave(filename = file.path(temp_dir, glue("{cyl}.png")), plot = plots)
    }
  )

# 方法2
# cyl_mtcars %>%
#   pwalk(
#     function(cyl, plots, ...) {
#       ggsave(filename = file.path(temp_dir, glue("{cyl}.png")), plot = plots)
#     }
#   )

备注:内容来源于stack exchange,提问作者r.bot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 07:13:04