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

针对列表输入,辅助函数中复用match.arg的优化方案问询

问题:优化match.arg处理形式参数的类型问题

免责声明:撰写此问题时已找到可行解决方案,但并不认可其合理性。因曾在另一线程提及该问题,故在此发布问题与方案,供有相同困扰者参考或提供更优解。

当前正在实现一个函数,不同「模块」存在同名输入变量但可设不同值,因此采用列表为每个模块指定输入。希望在字符型变量上使用match.arg,且因所有模块参数选项一致,编写了辅助函数避免重复代码。

现有代码

辅助函数与模块函数

match_arguments <- function(argument_list, choices_list) {
  matched_args <- mapply(match.arg, argument_list, choices_list) 
  return(as.list(matched_args))
}


part1_fun <- function(x = 1, y = TRUE, z = c("abc", "zyx"), another = c("aat", "bbt")) {
  arguments_to_match <- list(z = z, another = another)
  choices <- formals(part1_fun)[c("z", "another")]
  remaining_arguments <- formals(part1_fun)[!(names(formals(part1_fun)) %in% names(choices))]
  matched_arguments <- match_arguments(arguments_to_match, choices)
  matched_arguments <- lapply(matched_arguments, as.character)
  
  result <- c(remaining_arguments, matched_arguments)
  
  return(result)
}

示例调用代码

part2_fun <- function(x = 2, y = FALSE, z = "bcd"){
  list(x = x, y = y, z = z)
}


myFUN <- function(part1_args, part2_args){
  part1_input <- do.call(part1_fun, part1_args)
  part2_input <- do.call(part2_fun, part2_args)


  print(part1_input)
  print(part2_input)
}

part1_output <- myFUN(
  part1_args = list(x = 3, z = "z", another = "a"),
  part2_args = list(y = TRUE)
)

原问题

使用choices <- formals(part1_fun)[c("z", "another")]获取的是language类型对象而非字符向量:

List of 2
 $ z      : language c("abc", "zyx")
 $ another: language c("aat", "bbt")

这导致输出出现异常格式:

$x
[1] 1

$y
[1] TRUE

$z
"zyx"()

$another
"aat"()

当前临时解决方案

目前通过matched_arguments <- lapply(matched_arguments, as.character)将结果转为字符类型解决问题,但这种写法较为繁琐,是否有更简洁的优化方案?


内容的提问来源于stack exchange,提问作者Finn Lübber

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:33:19