在S3类的情况下如何处理更多参数? [英] How to handle further parameters in case of S3 classes?

查看:41
本文介绍了在S3类的情况下如何处理更多参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下三个基本相同的
版本(请参见下面的可复制示例):

Consider the following three versions which basically do the same (see reproducible example below):


  1. fun.class1<-函数(x,...)

  2. fun.class2<-函数(x)

  3. fun.class3<-function(x,y) [想法:我想具体说明我需要的
    ,所以我想我明确添加了命名参数]

  1. fun.class1 <- function(x, ...)
  2. fun.class2 <- function(x)
  3. 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]

问题:


  1. 为什么起作用?2。我在Hadley Advanced R中找不到任何内容。我也
    寻找了 ?? UseMethod ,但是如果我什么都没错过,那么就没有
    写到像 y 在我的情况下可以处理吗?

  2. 第三个版本在 print(y)处引发错误。我觉得这很有道理( y my_fun 中是未知的)。这个解释正确吗?

  3. 没有 print(y),函数运行通过,输出为 1 2 。由于 y = 1 无法移交给 UseMethod ,因此y被视为缺少参数,第三个变量 fun.class3 通常是方法的错误定义吗?

  1. 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 like y in my case are handled?
  2. The third version throws an error at print(y). I feel like this makes sence (y is not known in my_fun). Is this explanation correct?
  3. Without "print(y)", the function runs through and the output is 1 2 again. As y = 1 cannot be handed over to UseMethod, y is treated as missing argument and the third variant fun.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!

也许这是问题与之相关。

推荐答案

回答您的问题:


  1. 您的第二个版本有效,因为它在全局环境中找到了 y 。 (实际上,您的所有示例都在其中找到 y ,因为您从未将其传递给 my_fun

  2. 是的,这是正确的: my_fun 的接口希望您传递一个您不输入的参数 y 't pass。所以会引发错误。

  3. 不,第三个版本不错或不正确。另请参见此处

  1. Your second version works, because it finds y in the global environment. (Actually all of your examples find y there, since you never pass it to my_fun.
  2. Yes, that's correct: The interface of my_fun expects that you pass an argument y that you don't pass. So it throws an error.
  3. No, the third version is not bad or wrong. See also here

这篇关于在S3类的情况下如何处理更多参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆