使用R经由S4 setMethod()的方法调度:单个数字元素与数字向量

时间:2017-02-21 14:27:27

标签: 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",
    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.")  
        }
    })

具体来说,问题在于我无法区分两种用例:

  • 在第一种情况下,我只想传递单个数字元素,例如discrimination = 1.5difficulty = 2theta = 0.98
  • 在第二种情况下,我想传递数字向量,例如discrimination = c(1.5, 1.7, 1.9)difficulty = c(1.5, 2, 3.5)theta = c(1.1, 1.2, 1.3, 1.4 etc.)

我尝试探索不同的类型,但似乎R将单个元素存储为单元素向量。

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

你知道我怎么能摆脱这种情况?

0 个答案:

没有答案