Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 我可以定义在S3泛型的多个参数上分派的S4方法吗?_R_S4 - Fatal编程技术网

R 我可以定义在S3泛型的多个参数上分派的S4方法吗?

R 我可以定义在S3泛型的多个参数上分派的S4方法吗?,r,s4,R,S4,我想定义一个封装实际模型的包装类,让用户使用新的数据帧或模型矩阵调用predict(): raw_model <- ... model <- Model(raw_model) X <- matrix(...) predict(model, X) df <- data.frame(...) predict(model, df) }) 但是,对setMethod的两个调用都会失败 Error in matchSignature(signature, fdef) : m

我想定义一个封装实际模型的包装类,让用户使用新的数据帧或模型矩阵调用
predict()

raw_model <- ...
model <- Model(raw_model)
X <- matrix(...)
predict(model, X)
df <- data.frame(...)
predict(model, df)
})

但是,对
setMethod
的两个调用都会失败

Error in matchSignature(signature, fdef) : 
  more elements in the method signature (2) than in the generic signature (1) for function ‘predict’

我知道S4泛型是从S3泛型
predict
创建的,它的签名只接受一个命名参数
对象
,但是有没有办法让S4方法对多个第一个参数进行分派?

您可以对多个参数进行S4泛型分派,但(目前)无法对命名参数和
进行分派。这就是predict的问题-唯一命名的参数是
object

尽管如此,您仍然可以通过定义自己的通用“向下一级”来实现您想要的

predict2 <- function(model,newdata){stats::predict(model,newdata)}
setGeneric("predict2",signature=c("model","newdata"))

setMethod(
  "predict2",
  signature=c("Model","data.frame"),
  definition=function(model,newdata){
    matrix <- model.matrix(newdata) # or something like that
    stats::predict(object@model, matrix)
  }
)
predict2
predict2 <- function(model,newdata){stats::predict(model,newdata)}
setGeneric("predict2",signature=c("model","newdata"))

setMethod(
  "predict2",
  signature=c("Model","data.frame"),
  definition=function(model,newdata){
    matrix <- model.matrix(newdata) # or something like that
    stats::predict(object@model, matrix)
  }
)