flo*_*del 2 r matrix dataframe
我有一些与编写可以在矩阵和data.frames上工作的函数有关的问题.想象一下例如:
DoubleThatThing <- function(thing) {
stopifnot(is.matrix(thing) | is.data.frame(thing))
2 * thing
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:
是否存在矩阵或data.frame对象的通用术语?东西来取代Thing在DoubleThatThing.
是否有一个普遍接受或广泛使用的变量名称thing?
是is.matrix(thing) | is.data.frame(thing)测试此类对象的最佳方法吗?
我不确定这是否会对你有所帮助,或者这是否能满足你的需求.但为什么不声明generic method和定义方法matrix和data.frame?? 这是一个虚拟/愚蠢的例子:
# generic method
my_fun <- function(x, ...) {
UseMethod("my_fun", x)
}
# default action
my_fun.default <- function(x, ...) {
cx <- class(x)
stop(paste("No method defined for class", cx))
}
# method for object of class data.frame
my_fun.data.frame <- function(x, ...) {
print("in data.frame")
tapply(x[,1], x[,2], sum)
}
# method for object of class matrix
my_fun.matrix <- function(x, ...) {
print("in matrix")
my_fun(as.data.frame(x))
}
# dummy example
df <- data.frame(x=1:5, y=c(1,1,1,2,2))
mm <- as.matrix(df)
> my_fun(df)
# [1] "in data.frame"
# 1 2
# 6 9
> my_fun(mm)
# [1] "in matrix"
# [1] "in data.frame"
# 1 2
# 6 9
> my_fun(as.list(df))
# Error in my_fun.default(as.list(df)) : No method defined for class list
Run Code Online (Sandbox Code Playgroud)