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

如何验证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:
    foo('nwk', rooted = 'yes')
    
    Returns:
    Error in foo("nwk", rooted = "yes") : 'rooted' must be a logical value (TRUE or FALSE)
    
  • Passing NA (which is logical but not TRUE/FALSE):
    foo('nxs', rooted = NA)
    
    Returns:
    Error in foo("nxs", rooted = NA) : 'rooted' should be one of TRUE, FALSE
    
  • Valid inputs like foo('nwk', rooted = FALSE) or the default foo('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 like NA or NaN that are technically logical but not valid for your use case. If you want to allow NA, you can omit this second check.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:35:01