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

如何在不使用‘...’及指定函数的情况下检查R函数输入参数存在性

Checking if a Function Argument is Provided Without Forbidden Functions in R

Great question! Since you can't use the standard tools like missing(), hasArg(), exists(), or the ... construct, we can solve this by using a unique default value marker—an object that's so specific, users won't accidentally pass it in. Here's how to implement it:

Step 1: Create a Unique Marker Object

First, make a custom object that acts as our "missing argument" flag. We'll use a structured object with a unique class to ensure it's distinct from any regular value a user might pass:

# Create a one-of-a-kind marker for missing arguments
missing_marker <- structure(list(), class = "custom_missing_marker")

Step 2: Define Your Function

Set this marker as the default value for the arguments you want to check. Then use identical() to test if the argument still holds the marker (meaning the user didn't provide it):

fun <- function(x, y = missing_marker, z = missing_marker) {
  # Check if y was not provided (still has the default marker)
  notexist <- identical(y, missing_marker)
  return(notexist)
}

Step 3: Test the Function

Let's verify it works as expected:

  • When you call fun(x = 5) (no y provided):
    fun(x = 5)
    # Returns TRUE
    
  • When you call fun(x = 5, y = 10) (y is provided):
    fun(x = 5, y = 10)
    # Returns FALSE
    
  • Even if a user passes y = NULL (which counts as providing the argument), it correctly returns FALSE:
    fun(x = 5, y = NULL)
    # Returns FALSE
    

Why This Works

The missing_marker is a unique object—no regular input (numbers, strings, NULL, etc.) will ever be identical to it. Using identical() ensures we're checking exactly whether the argument was left at its default (unprovided) state, not just if its value is NULL (which your original example did, but that can give false positives if a user intentionally passes NULL).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:09:25