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

如何修正自定义函数传递函数与参数时的IQR调用错误?

问题修正方案

错误原因

  1. 原代码错误移除了na.rm参数,导致调用IQR时无法正确传递该逻辑参数,而IQR默认要求na.rm为逻辑值,空参数传递会触发长度为0的判断错误。
  2. 使用unlist(args)传递参数会破坏命名参数结构,无额外参数时会生成长度0的向量,触发IQR的参数校验失败。

修正后的函数代码

new_func <- function(.data, .x, .fns, ...){  
  # Arguments
  value_var_expr <- rlang::enquo(.x)
  func <- .fns
  func_chr <- deparse(substitute(.fns))
  passed_args <- list(...)
  
  # 保留所有传递参数,移除错误的na.rm过滤逻辑
  args <- passed_args
  
  ret <- purrr::map(
    .x = dplyr::as_tibble(.data), 
    .f = ~ do.call(func, c(list(.x), args)) %>%  # 用do.call正确传递命名参数列表
      purrr::imap(.f = ~ cbind(.x, name = .y)) %>%
      purrr::map_df(dplyr::as_tibble)
  ) %>%
    purrr::imap(.f = ~ cbind(.x, sim_number = .y)) %>%
    purrr::map_df(dplyr::as_tibble) %>%
    dplyr::select(sim_number, name, .x) %>%
    dplyr::mutate(.x = as.numeric(.x)) %>%
    dplyr::mutate(sim_number = factor(sim_number)) %>%
    dplyr::rename(value = .x)
  
  cn <- c("sim_number", "name", func_chr)
  names(ret) <- cn
  
  return(ret)
  
}

测试验证

  • 无额外参数调用:
new_func(mtcars, mpg, IQR)

可正常输出结果,无报错。

  • 传递na.rm=TRUE调用:
new_func(mtcars, mpg, IQR, na.rm = TRUE)

正常运行,正确处理缺失值(若数据存在缺失)。

  • 传递type=7调用:
new_func(mtcars, mpg, IQR, type = 7)

保持原有正常运行的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 17:35:25