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

如何编写R函数按多参数计算探访祖父母的等待时间或可探访日期

R函数visit_grandparent实现方案

实现思路

完全用命名向量映射规则替代多分支if判断,逻辑清晰易维护,同时集成lubridate包的日期函数直接计算可探访日期。

前置依赖

需要先安装加载lubridate包处理日期运算:

install.packages("lubridate")
library(lubridate)

完整函数代码

visit_grandparent <- function(sex, vacation, covid = NULL) {
  # 处理covid空值,默认按未感染新冠计算
  if (is.null(covid)) {
    covid <- "no"
  }
  
  # 参数合法性校验
  stopifnot(
    sex %in% c("male", "female"),
    vacation %in% c("yes", "no"),
    covid %in% c("yes", "no")
  )
  
  # 规则映射表,全量替代if分支
  base_wait <- c("male" = 2, "female" = 1)
  vacation_add <- c("yes" = 1, "no" = 0)
  covid_add <- c("no" = 1, "yes" = 0)
  
  # 计算总等待时长
  total_month <- base_wait[sex] + vacation_add[vacation] + covid_add[covid]
  # 计算最早可探访日期
  visit_date <- today() + months(total_month)
  
  # 返回结构化结果
  return(list(
    总等待时长 = paste0(total_month, "个月"),
    最早可探访日期 = as.character(visit_date)
  ))
}

调用测试

  • 未度假且感染过新冠的男性:visit_grandparent(sex = "male", vacation = "no", covid = "yes"),返回等待时长2个月,符合规则
  • 度假且未感染新冠的女性:visit_grandparent(sex = "female", vacation = "yes", covid = "no"),返回等待时长3个月,符合规则
  • 你示例的covid为NULL的调用:visit_grandparent(sex="female", vacation="yes", covid=NULL),会默认按未感染计算,返回3个月等待时长

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:57:02