gpt4 book ai didi

R S3 类 - 更改类并传回相同的方法

转载 作者:行者123 更新时间:2023-12-03 19:15:55 25 4
gpt4 key购买 nike

我有一个关于在 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)
}

这有效。当我执行以下操作时,我得到类 character对彼此而言
> my_func("hello")
[1] ".x is hello of class character"
> my_func(1)
[1] ".x is 1 of class character"

我的问题是:这是正确的方法吗?在我转换类之后重新调用相同的方法感觉很奇怪(这一行 res <- my_func(.x) )。

我觉得 NextMethod()必须以某种方式成为答案,但我已经阅读了一堆文档(例如 thisthis),但他们都在谈论这件事,它正在跳到类列表中的下一个类,比如来自 data.frame高达 matrix当你有 class(df)并获取 c("data.frame", "matrix")例如。

但是他们都没有谈论这种情况,即您将其转换为不在原始层次结构中的完全不同的类。所以也许 NextMethod()不是正确使用的东西,但是还有其他东西,还是我应该像拥有​​它一样离开它?

谢谢!

最佳答案

1) 如果想法是 my_func.numeric 做了额外的处理,但又想使用 my_func.character 而不重复,那么在 func.numeric设置 .Class然后调用NextMethod像这样:

my_func.numeric <- function(.x, ...) {
.Class <- "character"
.x <- as.character(.x)
NextMethod()
}
NextMethod返回一个结果,并且可以选择在它之后进行其他处理。更多信息可以通过发布 ?NextMethod 找到。在 R。

2) 如果想法是可以组合数字和字符方法,那么:
my.func.character <- my.func.numeric <- function(.x, ...) {
.x <- as.character(.x)
paste(".x is", .x, "of class", class(.x))
}

如果尚未将其用于其他用途,也可以为此使用默认方法。

3) 如果想法只是有共享功能,但您不一定想在数字方法中使用所有字符方法处理,反之亦然,那么定义一个由每个方法调用的函数:
my_func_impl <- function(.x, ...) paste(".x is", .x, "of class", class(.x))

my_func.character <- function(.x, ...) {
# some procesing unique to this method
my_func_impl(.x, ...)
}

my_func.numeric <- function(.x, ...) {
# some procesing unique to this method
my_func_impl(.x, ...)
}

关于R S3 类 - 更改类并传回相同的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60641142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com