R语言中向NextMethod()传入generic参数的作用与目的是什么?
理解R语言中
NextMethod()的generic参数作用 示例
# 示例数据 x <- as.Date(c("2022-01-01", "2023-01-01", "1900-01-01", "2024-01-01")) # 按预期返回累积最大值 cummax.Date <- function(x, ...) .Date(NextMethod(), cl = oldClass(x)) cummax(x) #> [1] "2022-01-01" "2023-01-01" "2023-01-01" "2024-01-01" # 按预期返回累积最小值 cummin.Date <- function(x, ...) .Date(NextMethod(), cl = oldClass(x)) cummin(x) #> [1] "2022-01-01" "2022-01-01" "1900-01-01" "1900-01-01"
最佳实践
在实际开发的最佳实践中,建议显式指定泛型函数:
cummin.Date <- function(x, ...) .Date(NextMethod(generic = "cummin"), cl = oldClass(x)) cummin(x) #> [1] "2022-01-01" "2022-01-01" "1900-01-01" "1900-01-01"
不良实践——无差异
不过需要注意,显式指定的泛型函数无论是否真实存在,都不会影响最终执行结果:
# 仍然返回累积最小值 cummin.Date <- function(x, ...) .Date(NextMethod(generic = "cummax"), cl = oldClass(x)) cummin(x) #> [1] "2022-01-01" "2022-01-01" "1900-01-01" "1900-01-01" # 仍然返回累积最小值 cummin.Date <- function(x, ...) .Date(NextMethod(generic = "foobar"), cl = oldClass(x)) cummin(x) #> [1] "2022-01-01" "2022-01-01" "1900-01-01" "1900-01-01"
内容的提问来源于stack exchange,提问作者mnist
相关产品推荐
相关产品推荐

