我正在尝试使用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.5
,difficulty = 2
,theta = 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
你知道我怎么能摆脱这种情况?