如果我需要根据它们的类以不同的方式处理 R 对象,我可以在单个函数中使用if和else:
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)
每种方法的优点是什么?有性能影响吗?