在S3类的情况下如何处理更多参数? [英] How to handle further parameters in case of S3 classes?
本文介绍了在S3类的情况下如何处理更多参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下三个基本相同的
版本(请参见下面的可复制示例):
Consider the following three versions which basically do the same (see reproducible example below):
-
fun.class1<-函数(x,...)
-
fun.class2<-函数(x)
-
fun.class3<-function(x,y)
[想法:我想具体说明我需要的
,所以我想我明确添加了命名参数]
fun.class1 <- function(x, ...)
fun.class2 <- function(x)
fun.class3 <- function(x, y)
[Idea: I would like to be specific in what I need, so I thought I explicitly add the named arguments]
问题:
- 为什么起作用?2。我在Hadley Advanced R中找不到任何内容。我也
寻找了?? UseMethod
,但是如果我什么都没错过,那么就没有
写到像y
在我的情况下可以处理吗? - 第三个版本在
print(y)
处引发错误。我觉得这很有道理(y
在my_fun
中是未知的)。这个解释正确吗? - 没有
print(y)
,函数运行通过,输出为1 2
。由于y = 1
无法移交给UseMethod
,因此y被视为缺少参数,第三个变量fun.class3
通常是方法的错误定义吗?
- Why does 2. work? I didn't find anything in Hadley "Advanced R". I also
looked for
??UseMethod
but if I don't miss anything, there's nothing written about how the arguments likey
in my case are handled? - The third version throws an error at
print(y)
. I feel like this makes sence (y
is not known inmy_fun
). Is this explanation correct? - Without "
print(y)
", the function runs through and the output is1 2
again. Asy = 1
cannot be handed over toUseMethod
, y is treated as missing argument and the third variantfun.class3
is in general a bad or wrong definition of a method?
可复制的示例:
fun.default <- function(x) {
print("default")
return(x)
}
fun.class1 <- function(x, ...) {
print("class1 ellipsis")
res <- x[y]
return(res)
}
fun.class2 <- function(x) {
print("class2 only x")
res <- x[y]
return(res)
}
fun.class3 <- function(x, y) {
print("class3 x and y")
# print(y) # Error in print(y) : argument "y" is missing, with no default
res <- x[y]
print(res)
return(res)
}
my_fun <- function(x) {
res <- UseMethod("fun")
return(res)
}
x <- structure(c(1, 2), class = c("numeric", "class1"))
y <- 1
my_fun(x)
# [1] "class1 ellipsis"
# [1] 1
x <- structure(c(1, 2), class = c("numeric", "class2"))
y <- 1
my_fun(x)
# [1] "class2 only x"
# [1] 1
x <- structure(c(1, 2), class = c("numeric", "class3"))
y <- 1
my_fun(x)
# [1] "class3 x and y"
# [1] 1 2
# [1] 1 2 # Why a second time? y = 1!
也许这是问题与之相关。
推荐答案
回答您的问题:
- 您的第二个版本有效,因为它在全局环境中找到了
y
。 (实际上,您的所有示例都在其中找到y
,因为您从未将其传递给my_fun
。 - 是的,这是正确的:
my_fun
的接口希望您传递一个您不输入的参数y
't pass。所以会引发错误。 - 不,第三个版本不错或不正确。另请参见此处
- Your second version works, because it finds
y
in the global environment. (Actually all of your examples findy
there, since you never pass it tomy_fun
. - Yes, that's correct: The interface of
my_fun
expects that you pass an argumenty
that you don't pass. So it throws an error. - No, the third version is not bad or wrong. See also here
这篇关于在S3类的情况下如何处理更多参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文