通过S4 setMethod()使用R进行方法调度:单个数值元素与数值向量

通过S4 setMethod()使用R进行方法调度:单个数值元素与数值向量,r,vector,methods,overloading,s4,R,Vector,Methods,Overloading,S4,我试图使用S4泛型方法,并根据正在传递的对象的签名调用正确的方法 以下是我迄今为止所做的工作: setGeneric( name = "_get_prob_2pl", def = function(discrimination, difficulty, theta) { standardGeneric("_get_prob_2pl") }) # # case 1 setMethod( f = "_get_prob_2pl", sig

我试图使用
S4
泛型方法,并根据正在传递的对象的签名调用正确的方法

以下是我迄今为止所做的工作:

setGeneric(
    name = "_get_prob_2pl",
    def = function(discrimination, difficulty, theta) {
        standardGeneric("_get_prob_2pl")
    })



# # case 1 
setMethod(
    f = "_get_prob_2pl",
    signature = "numeric", # also tried "double" and "integer"
    definition = function(discrimination, difficulty, theta) 
    {
        x = exp(1) ^ (discrimination * (theta - difficulty)) 
        return(x / (1 + x))
    })



# # case 2
setMethod(
    f = "_get_prob_2pl",
    signature = "vector",
    definition = function(discrimination, difficulty, theta) 
    {
        if(length(discrimination) == length(difficulty)) {  
            responses <- NULL
            temp_respondent_row <- NULL

            for(i in 1:length(theta)) 
            {
                for(j in 1:length(discrimination)) 
                {   
                    temp_respondent_row[j] = get_prob_2pl(discrimination[j], difficulty[j], theta[i])
                }

                responses <- rbind(responses, temp_respondent_row)
            }
            rownames(responses) <- NULL
            return(responses)

        } else {    
            stop("The length of vectors 'discrimination' and 'difficulty' must be equal, Their length give the number of items.")  
        }
    })

你知道我怎样才能摆脱这种情况吗?

在R中没有标量值的概念,所以是的
1.5
是长度为1的向量“R将单个元素存储为一个元素向量”。“你知道我怎样才能摆脱这种情况吗?”
if(length(x)=1L)
?也许你可以测试数字的长度,如果它大于1,你可以使用
nextMethod
发送向量签名。在
numeric
方法的主体顶部,尝试输入
if(length(x)=1L)NextMethod()
。不确定这是否有效,但值得一试。Length-one向量没有特定的类,因此无法对其应用特定的方法。但是,您不应该需要这个。如果确实需要对长度为1的向量进行特定处理,只需在方法中使用
if
条件。但你为什么要这么做?在你的例子中,你当然不会<代码>用于(i in 1)工作正常。附言:我不认为向量是一个类。PPS:当然,我会用矢量化的方法来代替你的循环。
x <- c(1, 2, 3)
y <- 1.5

typeof(x) # double
typeof(y) # double


is.vector(x) # TRUE
is.vector(y) # TRUE

is.double(x) # TRUE
is.double(y) # TRUE

is.integer(x) # FALSE
is.integer(y) # FALSE