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

如何修改R代码以检查函数第一个参数是否为指定值?

检查函数第一个参数是否为指定名称

现有代码能够检查函数是否包含任意指定名称的形参:

# 定义测试函数
f <- function (a, b, c)
{
    1
}

# 检查函数是否包含任意指定名称的参数
check_if_any_argument_is_certain_value <- function(f, x) {
  x %in% names(formals(f))
}

check_if_any_argument_is_certain_value(f, "b") # 返回 TRUE
#> [1] TRUE
check_if_any_argument_is_certain_value(f, "d") # 返回 FALSE
#> [1] FALSE

现在需要修改代码,实现仅检查第一个参数的名称是否等于指定值,期望效果如下:

check_if_first_argument_is_certain_value <- function(f, x) 
{# 待实现代码}

check_if_first_argument_is_certain_value(f, "a") # 返回 TRUE
check_if_first_argument_is_certain_value(f, "b") # 返回 FALSE

解决方案

只需要提取函数第一个形参的名称,再与目标值直接比较即可,修改后的代码如下:

check_if_first_argument_is_certain_value <- function(f, x) {
  names(formals(f))[1] == x
}

验证测试

# 匹配第一个参数的情况
check_if_first_argument_is_certain_value(f, "a")
#> [1] TRUE

# 不匹配的情况
check_if_first_argument_is_certain_value(f, "b")
#> [1] FALSE

原理说明:formals(f)会返回函数的形参列表,names(formals(f))提取出所有形参的名称,通过[1]取第一个名称,最后用==和目标值x比较,返回布尔结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 07:35:17