gpt4 book ai didi

R:在全局环境中从包 ‘split’ 为 ‘base’ 创建通用函数

转载 作者:行者123 更新时间:2023-12-05 06:44:38 27 4
gpt4 key购买 nike

为简单起见,我将使用以下示例代码:)

我已经定义了一个S4类test,然后像往常一样我采用setMethod为类test编写泛型函数split :

# define a S4 class
setClass(
Class="test",
representation=representation(
m = "matrix"
)
)

# write generic function 'split' for S4 class 'test'
setMethod(f = "split", signature = c("test"), function(x, f) {
split(x@m, f)
})

# call generic function for test
split(new("test", m=matrix(1:9,3)), c(1,2,3))

运行上面的代码,R命令行会给出如下信息:

Creating a generic function for ‘split’ from package ‘base’ in the global environment

然后程序输出如下:

$`1`
[1] 1 4 7

$`2`
[1] 2 5 8

$`3`
[1] 3 6 9

看来输出是正确的。但我的问题是如何抑制消息:

Creating a generic function for ‘split’ from package ‘base’ in the global environment

非常感谢:)

附言:我发现将 S4 类 test 的方法 split 的定义替换为 我们如何实现 S3 泛型方法的形式 如下将摆脱该消息:

split.test <- function(x, f) {
split(x@m, f)
}

但是,我认为混合使用 S3 和 S4 不是一个好主意:)

最佳答案

这是 S4 类的一个不幸的事实问题。黄金标准通常被称为 Matrix 包。他们还巧妙地避免了这个问题:重载 rownamescolnames(在 base 中定义)直接产生相同的警告。但是检查这些函数会发现它们是 dimnames 函数的便利函数:

> colnames
function (x, do.NULL = TRUE, prefix = "col")
{
if (is.data.frame(x) && do.NULL)
return(names(x))
dn <- dimnames(x)
# ...
}
> rownames
function (x, do.NULL = TRUE, prefix = "row")
{
dn <- dimnames(x)
# ...
}
> dimnames
function (x) .Primitive("dimnames")

Matrix 包通过定义一个针对dimnames 的泛型来避免这个问题。正如 Michael 上面评论的那样,最好的选择是重载 [ 运算符,它同样是原始的:

> `[`
.Primitive("[")

再次借鉴 Matrix 包,一个建议是:

setMethod("[", signature(x = "sparseMatrix", i = "missing", j = "index",
drop = "logical"),
function(x, i, j, ..., drop) {
# add any behavior for ...
`[`(x@m, i, j, drop=drop)
}
)

这还使用 [ 运算符从其他通用函数中添加了许多自由行为。

关于R:在全局环境中从包 ‘split’ 为 ‘base’ 创建通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28321655/

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