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

如何将pmap与ggplot函数集成?解决调用时filter方法报错问题

问题解决:pmap调用ggplot函数时报错UseMethod("filter")

报错原因

你创建的tibble里dat列存储的是数据框名称的字符串("penguins"),而非实际的penguins数据框对象。当pmap把字符串传给make_plot的dat参数时,filter函数无法对字符串类型执行操作,因此抛出报错。

解决方案

有两种简单的修正方式:

方法1:在tibble中存储数据框对象(推荐)

直接将数据框本身存入tibble的列中,利用tibble支持列表列的特性,用list()包裹数据框重复:

library(tidyverse)
library(palmerpenguins)

make_plot <- function(dat, species) {
  dat %>%
    filter(.data$species == .env$species) %>%
    ggplot() +
    aes(bill_length_mm, body_mass_g, color=sex) +
    geom_point() +
    ggtitle(glue("Species: {species}")) +
    xlab("bill length (mm)") +
    ylab("body mass (g)") +
    theme(plot.title.position = "plot")
}

species <- c("Adelie", "Chinstrap", "Gentoo")
# 修改dat列,存储数据框对象而非字符串
penguins_vars <- tibble(dat = rep(list(penguins), 3), species = species)

plots <- pmap(penguins_vars, make_plot)

# 验证成功
plots[[1]]

方法2:在函数内部将字符串转为数据框

如果需要保留字符串形式的数据框名称,可以在make_plot里用get()函数将字符串映射为实际的数据框对象:

library(tidyverse)
library(palmerpenguins)

make_plot <- function(dat, species) {
  # 用get()把字符串转为数据框
  get(dat) %>%
    filter(.data$species == .env$species) %>%
    ggplot() +
    aes(bill_length_mm, body_mass_g, color=sex) +
    geom_point() +
    ggtitle(glue("Species: {species}")) +
    xlab("bill length (mm)") +
    ylab("body mass (g)") +
    theme(plot.title.position = "plot")
}

species <- c("Adelie", "Chinstrap", "Gentoo")
penguins_vars <- tibble(dat = rep("penguins", 3), species = species)

plots <- pmap(penguins_vars, make_plot)

# 验证成功
plots[[2]]

说明

两种方法都能解决问题,方法1更直观且避免了字符串解析的潜在风险,是更推荐的做法。修改后pmap就能正确传递数据框给make_plot,生成对应的物种散点图。

内容的提问来源于stack exchange,提问作者Juan Manuel Schvartzman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:10:56