我的问题是你如何扩展rbind()
与data.frame
子类一起工作?我似乎无法正确扩展rbind()
甚至是一个非常简单的子类。以下示例演示了此问题:
子类和方法定义:
new_df2 <- function(x, ...)
{
stopifnot(is.data.frame(x))
structure(x, class = c("df2", "data.frame"), author = "some user")
}
rbind.df2 <- function(..., deparse.level = 1)
{
NextMethod()
}
我意识到在这种情况下扩展rbind()
不是必需的,但我的宏伟计划是在我的子类上使用rbind.data.frame()
,然后在其结果中添加一些额外的检查/属性。
如果您调用以下内容,则会收到错误:Error in NextMethod() : generic function not specified
。
不起作用:
t1 <- data.frame(a = 1:12, b = month.abb)
t2 <- new_df2(t1)
rbind(t2, t2)
我也尝试过使用NextMethod(generic = "rbind")
,但在这种情况下,你会收到这个错误:Error in NextMethod(generic = "rbind") : wrong value for .Method
。
也不起作用:
rbind.df2 <- function(..., deparse.level = 1)
{
NextMethod(generic = "rbind")
}
rbind(t2, t2)
我在智慧结束时猜测我对子类/方法的理解的极限。谢谢你的帮助。
我将在下面讨论rbind()
特定情况,但我首先要注意,我们可以生成其他示例,表明当第一个参数是NextMethod()
(关于赏金请求)时,...
通常没有问题:
f <- function(..., b = 3) UseMethod("f")
f.a <- function(..., b = 3) { print("yes"); NextMethod() }
f.integer <- function(..., b = 4) sapply(list(...), "*", b)
x <- 1:10
class(x) <- c("a", class(x))
f(x)
[1] "yes"
[,1]
[1,] 4
[2,] 8
[3,] 12
[4,] 16
[5,] 20
[6,] 24
[7,] 28
[8,] 32
[9,] 36
[10,] 40
f(x, b = 5)
[1] "yes"
[,1]
[1,] 5
[2,] 10
[3,] 15
[4,] 20
[5,] 25
[6,] 30
[7,] 35
[8,] 40
[9,] 45
[10,] 50
事实证明,rbind()
和cbind()
不是正常的仿制药。首先,它们是内部通用的;请参阅Hadley Wickham在Advanced R上的旧S3页面的“内部泛型”部分here,或者从当前的Advanced R摘录:
某些S3泛型,如[,sum()和cbind(),不会调用UseMethod(),因为它们是用C实现的。相反,它们调用C函数DispatchGroup()或DispatchOrEval()。
这不足以引起我们的麻烦,正如我们可以看到使用sum()
作为一个例子:
sum.a <- function(x, na.rm = FALSE) { print("yes"); NextMethod() }
sum(x)
[1] "yes"
[1] 55
然而,对于rbind
和cbind
来说,它甚至更奇怪,正如在source code的评论中所认识的那样(从第1025行开始):
/* cbind(deparse.level, ...) and rbind(deparse.level, ...) : */
/* This is a special .Internal */
...(省略了一些代码)......
/* Lazy evaluation and method dispatch based on argument types are
* fundamentally incompatible notions. The results here are
* ghastly.
之后,给出了对调度规则的一些解释,但到目前为止,我还没有能够使用该信息来使NextMethod()
工作。在上面给出的用例中,我会从评论中遵循F. Privé的建议并执行此操作:
new_df2 <- function(x, ...)
{
stopifnot(is.data.frame(x))
structure(x, class = c("df2", "data.frame"))
}
rbind.df2 <- function(..., deparse.level = 1)
{
print("yes") # Or whatever else you want/need to do
base::rbind.data.frame(..., deparse.level = deparse.level)
}
t1 <- data.frame(a = 1:12, b = month.abb)
t2 <- new_df2(t1)
rbind(t2, t2)
[1] "yes"
a b
1 1 Jan
2 2 Feb
3 3 Mar
4 4 Apr
5 5 May
6 6 Jun
7 7 Jul
8 8 Aug
9 9 Sep
10 10 Oct
11 11 Nov
12 12 Dec
13 1 Jan
14 2 Feb
15 3 Mar
16 4 Apr
17 5 May
18 6 Jun
19 7 Jul
20 8 Aug
21 9 Sep
22 10 Oct
23 11 Nov
24 12 Dec
答案是扩展rbind2
,而不是rbind
。从rbind2
的帮助页面:
“这些是(S4)使用默认方法的通用函数。
...
当满足这两个要求时,cbind2(rbind2)的主要用途是由cbind()(rbind())递归调用: