我有一个关于在 R 中使用 S3 类执行某些操作的“正确”方法的问题。我想要做的是有一个方法可以更改类,然后在新类上调用相同的方法。像这样的东西:
my_func <- function(.x, ...) {
UseMethod("my_func")
}
my_func.character <- function(.x, ...) {
return(paste(".x is", .x, "of class", class(.x)))
}
my_func.numeric <- function(.x, ...) {
.x <- as.character(.x)
res <- my_func(.x) # this should call my_func.character
return(res)
}
Run Code Online (Sandbox Code Playgroud)
这有效。当我执行以下操作时,我会character同时获得课程
> my_func("hello")
[1] ".x is hello of class character"
> my_func(1)
[1] ".x is 1 of class character"
Run Code Online (Sandbox Code Playgroud)
我的问题是:这是正确的方法吗?在转换类之后重新调用相同的方法(这一行res <- my_func(.x))感觉很奇怪。
我觉得NextMethod()一定是答案,但我读过很多关于它的文档(例如这个和这个),但他们都讨论了这个事情,它跳到类列表中的下一个类,例如例如,data.frame直到matrix您拥有class(df)并获得时。c("data.frame", "matrix")
但他们都没有谈论这种情况,即您将其转换为不在原始层次结构中的完全不同的类。所以也许NextMethod() 这不是正确的使用方式,但是还有其他的东西,或者我应该像我拥有的那样保留它吗?
谢谢!
The most standard way would be to create a default method, something like:
my_func.default <- function(.x, ...) {
stopifnot(is.atomic(.x)) # throw an error if .x isn't an atomic vector
.x <- as.character(.x)
paste(".x is", .x, "of class", class(.x))
}
my_func("hello")
#> [1] ".x is hello of class character"
my_func(1)
#> [1] ".x is 1 of class character"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
297 次 |
| 最近记录: |