如何验证R自定义函数rooted参数为logical类型并返回错误提示
Got it! You want to add the same robust validation for the rooted parameter that tree_format already has in your foo function. Here's how to do it clearly and effectively:
Updated Function with Rooted Parameter Validation
foo <- function(tree_format, rooted = TRUE) { # Keep the existing validation for tree_format match.arg(tree_format, choices = c('nwk', 'nxs')) # Validate the rooted parameter # First check if it's a logical type if (!is.logical(rooted)) { stop("'rooted' must be a logical value (TRUE or FALSE)") } # Then ensure it's explicitly TRUE or FALSE (rejects NA/NaN) if (!(rooted %in% c(TRUE, FALSE))) { stop("'rooted' should be one of TRUE, FALSE") } # Add your core function logic here once validation passes }
Testing the Error Cases
Let's verify the validation works as expected:
- Passing a non-logical value for
rooted:
Returns:foo('nwk', rooted = 'yes')Error in foo("nwk", rooted = "yes") : 'rooted' must be a logical value (TRUE or FALSE) - Passing
NA(which is logical but not TRUE/FALSE):
Returns:foo('nxs', rooted = NA)Error in foo("nxs", rooted = NA) : 'rooted' should be one of TRUE, FALSE - Valid inputs like
foo('nwk', rooted = FALSE)or the defaultfoo('nxs')will run without errors.
Quick Breakdown of the Checks
!is.logical(rooted): Catches any input that isn't a logical type (strings, numbers, lists, etc.)!(rooted %in% c(TRUE, FALSE)): Ensures we only accept the explicit boolean values, excluding edge cases likeNAorNaNthat are technically logical but not valid for your use case. If you want to allowNA, you can omit this second check.
内容的提问来源于stack exchange,提问作者user3479780
相关产品推荐
相关产品推荐

