相关疑难解决方法(0)

`UseMethod()` 与 `inherits()` 在 R 中确定对象的类

如果我需要根据它们的类以不同的方式处理 R 对象,我可以在单个函数中使用ifelse

foo <- function (x) {
  if (inherits(x, 'list')) {
    # Foo the list
  } else if (inherits(x, 'numeric')) {
    # Foo the numeric
  } else {
    # Throw an error
  }
}
Run Code Online (Sandbox Code Playgroud)

或者我可以定义一个方法:

foo <- function (x) UseMethod('foo')

foo.list <- function (x) {
  # Foo the list
}
foo.numeric <- function (x) {
  # Foo the numeric
}
Run Code Online (Sandbox Code Playgroud)

每种方法的优点是什么?有性能影响吗?

oop r class

2
推荐指数
1
解决办法
231
查看次数

标签 统计

class ×1

oop ×1

r ×1