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

如何让purrr::pmap()忽略数据框中的多余列?

解决purrr::pmap()忽略数据框多余列的几种方法

当使用purrr::pmap()时,数据框中存在函数不需要的列会触发"unused argument"错误,以下是几种实用的解决思路:

1. 自动筛选函数所需列(推荐,灵活通用)

利用函数的参数名自动提取数据框中对应的列,不用手动指定列名,适配函数参数变更的场景:

library(tidyverse)

set.seed(123)
df <- tibble(a = runif(5),
             b = runif(5),
             c = runif(5),
             d = runif(5))

f <- function(a, b, d) a+b+d

# 通过函数参数名自动筛选列
pmap(df %>% select(all_of(rlang::fn_fmls_names(f))), f)

2. 包装函数以忽略多余参数

给原函数套一层包装,用...吸收所有多余参数,避免报错:

# 简单包装(针对特定函数)
f_wrap <- function(a, b, d, ...) f(a, b, d)
pmap(df, f_wrap)

# 通用包装器(可复用在任意函数)
ignore_extra_args <- function(.f) {
  required_args <- rlang::fn_fmls_names(.f)
  function(...) {
    input_args <- as.list(match.call())[-1]
    filtered_args <- input_args[names(input_args) %in% required_args]
    rlang::exec(.f, !!!filtered_args)
  }
}

# 使用通用包装器
pmap(df, ignore_extra_args(f))

3. 用tidyverse行操作替代pmap

如果更习惯直观的行级操作,rowwise()配合mutate可以直接指定需要的列,同时保留结果在数据框中:

df %>%
  rowwise() %>%
  mutate(result = f(a, b, d)) %>%
  pull(result)

4. 基础R实现方式

不用tidyverse的话,结合apply和do.call也能实现:

apply(df, 1, function(row) {
  do.call(f, as.list(row)[names(formals(f))])
})

内容的提问来源于stack exchange,提问作者max

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:25:30