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

S3调度异常:自定义to_from_fiscal类的as.factor方法未被调用

自定义S3类to_from_fiscal的as.factor方法调度问题

我创建了一个继承自Date类的自定义S3类to_from_fiscal,用于生成英国常用格式的财年。目标是为该类实现自定义的as.factor方法,以正确将财年对象转换为因子,但S3调度似乎无法识别自定义方法as.factor.to_from_fiscal。

实现代码

new_to_from_fiscal <- function(date = lubridate::Date(),
                               fiscal_start = integer(),
                               sep = character(),
                               short = logical()) {
  stopifnot(lubridate::is.Date(date))
  stopifnot(is.character(sep))
  stopifnot(is.integer(fiscal_start))
  stopifnot(fiscal_start >= 1 & fiscal_start <= 12)
  stopifnot(is.logical(short))
  
  structure(
    date,
    class = c("to_from_fiscal", "Date"),
    sep = sep,
    fiscal_start = fiscal_start,
    short = short
  )
}

# Create fiscal year object
to_from_fiscal <- function(date, fiscal_start = 4, sep = "-", short = FALSE) {
  date <- as.Date(date)
  fiscal_start <- as.integer(fiscal_start)
  sep <- as.character(sep)
  
  from_year <- lubridate::year(date) + ifelse(lubridate::month(date) >= fiscal_start, 0, -1)
  new_to_from_fiscal(as.Date(paste(from_year, fiscal_start, 1, sep = "-")), fiscal_start, sep, short)
}

# Format method for the custom class
format.to_from_fiscal <- function(x, ...) {
  fiscal_start <- attr(x, "fiscal_start")
  short <- attr(x, "short")
  sep <- attr(x, "sep")
  from_year <- lubridate::year(x)
  to_year <- from_year + 1
  if (isTRUE(short)) {
    sprintf("%02d%s%02d", from_year %% 100, sep, to_year %% 100)
  } else {
    sprintf("%d%s%d", from_year, sep, to_year)
  }
}

# Custom as.factor method
as.factor.to_from_fiscal <- function(x, ...) {
  factor(format(x, ...))
}

问题表现

  • 执行test_fq <- to_from_fiscal(as.Date("2024-05-15"), short = TRUE)后,调用factor(test_fq)返回NA
  • 使用sloop::s3_dispatch(as.factor(test_fq))检查,结果显示自定义方法存在但未被调用

已尝试操作

  • 确认to_from_fiscal是类属性的首类,class(test_fq)返回[1] "to_from_fiscal" "Date"
  • 验证format方法正常工作,format(test_fq)返回"24-25"

诊断信息

  • attributes(test_fq)确认自定义属性完整
  • sloop::s3_dispatch显示方法可用但未被调用

疑问

  • 为何S3调度未优先调用as.factor.to_from_fiscal?
  • 如何确保调用as.factor时正确调度该方法?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 22:29:56