Using callNextMethod() within accessor function in R

混江龙づ霸主 提交于 2019-12-04 06:54:53

Your methods both leave out one of the five formal arguments required by any [ method, namely the ellipsis (...).

args(getGeneric("["))
# function (x, i, j, ..., drop = TRUE) 
# NULL

Including it as a formal in both method definitions solves your problem:

setMethod("[", "bar", function(x, i, j, ..., drop) {
  if (i == "distance") {
    return(x@distance)
    } else {
      callNextMethod()
    }
}
)

setMethod("[", "foo", function(x, i, j, ..., drop) {
  if (i == "x") {
    return(x@x)
    } else {
      if (i == "y") {
        return(x@y)
      }
    }
}
)

b["distance"]
# [1] 5
b["x"]
# [1] 3
b["y"]
# [1] 4
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!