如何在不使用‘...’及指定函数的情况下检查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)(noyprovided):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

